package com.hotel.front;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.StatusTitle;
import com.Util;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.google.gson.Gson;
import com.hotel.BL.AgencyLogic;
import com.hotel.BL.ChargeLogic;
import com.hotel.BL.CreditCardLogic;
import com.hotel.BL.DNRLogic;
import com.hotel.BL.GenericLogic;
import com.hotel.BL.GuestLogic;
import com.hotel.BL.PaymentLogic;
import com.hotel.BL.ReservationLogic;
import com.hotel.BL.RoomLogic;
import com.hotel.BL.RoomTypeLogic;
import com.hotel.BL.SubReservationLogic;
import com.hotel.BL.TaxLogic;
import com.hotel.BL.TravelLogic;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import data.Agency;
import data.Charge;
import data.CreditCard;
import data.DNR;
import data.Group;
import data.Guest;
import data.PackageByDate;
import data.Reservation;
import data.ReservationStatus;
import data.Room;
import data.RoomType;
import data.SubReservation;
import data.travel;
import data.passingData.EffectedRoom;
import data.passingData.GuestData;
import data.passingData.PaymentData;
import data.passingData.ReservationData;
import data.passingData.ReservationDataForReport;
import data.passingData.ReservationDataFull;
import data.passingData.ReservationDataFullWithTask;
import data.passingData.ResultCreResData;
import data.passingData.ResultData;

@SuppressWarnings("serial")
public class ReservationService extends HttpServlet {
	// localhost:8080/reservationService?func=GetReservationList&span=3&date=2013-1-21
	// localhost:8080/reservationService?func=addReservationStatus&title=Cancel Check-in&color=#FFFFFF
	// localhost:8080/reservationService?func=CreateRessample
	// localhost:8080/reservationService?func=CreateRes&date=yyyy-MM-dd&span=3&rmId=roomId&rmType=roomTypeId&rmNum=1&priceRate=priceRateId&adult=adult&child=child&dep=500.00&isA=false&timeStamp=timeStamp
	// &sal=salutatinId&guest=guestId&nm=Name&lsNm=LastName&phone=phone&isMobile=true&mail=mail
	// &agency=agencyId&agencyName=agencyName
	// localhost:8080/reservationService?func=editAfterRes&resId=reservationId&reservationstatus=ReservationStatus
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String func = req.getParameter("func");
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		try {
			if (func.equals("GetReservationList")) {
				GetReservationList(hotelId, req, resp);
			}
			else if (func.equals("CreateRes")) {
				CreateReservation(hotelId, req, resp);
			}
			else if (func.equals("editAfterRes")) {
				EditAfterReservation(hotelId, req, resp);
			}
			else if (func.equals("removeRes")) {
				RemoveResFormDatastore(req, resp);
			}
			else if (func.equals("removeResTemp")) {
				RemoveResTempFormDatastore(req, resp);
			}
			else if (func.equals("editNote")) {
				EditNote(req, resp);
			}
			else if (func.equals("EditGuestData")) {
				EditGuestData(req, resp);
			}
			else if (func.equals("loadGroup")) {
				LoadGroup(req, resp);
			}
			else if (func.equals("loadGroupResvList")) {
				LoadGroupResvList(req, resp);
			}
			else if (func.equals("loadGroupResvListCancel")) {
				LoadGroupResvListCancel(req, resp);
			}
			else if (func.equals("GetIdTaskList")) {
				GetIdTaskList(req, resp);
			}
			else if (func.equals("editDetailGroup")) {
				EditDetailGroup(req, resp);
			}
			else if (func.equals("editDetailReservation")) {
				EditDetailReservation(req, resp);
			}
			else if (func.equals("GetIdTaskListGroup")) {
				GetIdTaskListGroup(req, resp);
			}
			else if (func.equals("editSpanS")) {
				EditSpanS(req, resp);
			}
			else if (func.equals("editNameS")) {
				EditNameS(req, resp);
			}
			else if (func.equals("editRoomtypeS")) {
				EditRoomtypeS(req, resp);
			}
			else if (func.equals("editRoomS")) {
				EditRoomS(req, resp);
			}
			else if (func.equals("editRoomStatusS")) {
				EditRoomStatusS(req, resp);
			}
			else if (func.equals("editPackageS")) {
				EditPackageS(req, resp);
			}
			else if (func.equals("newResInGroup")) {
				AddResInGroup(req, resp);
			}
			else if (func.equals("editAdultS")) {
				EditAdultS(req, resp);
			}
			else if (func.equals("editChildS")) {
				EditChildS(req, resp);
			}
			else if (func.equals("editDateS")) {
				EditDateS(req, resp);
			}
			else if (func.equals("getReservation")) {
				GetReservation(req, resp);
			}
			else if (func.equals("getReservationAllCheckoutOnly")||func.equals("getReservationAllCheckoutOnlyGroup")||func.equals("getReservationAllCheckoutOnlySingle")
					||func.equals("getReservationExpressCheckOut")||func.equals("getReservationExpressCheckOutGroup")||func.equals("getReservationExpressCheckOutSingle")
					||func.equals("getReservationAllGuestName")||func.equals("getReservationAllGuestNameGroup")||func.equals("getReservationAllGuestNameSingle")
					||func.equals("getReservationAllPaymentTracker")||func.equals("getReservationAllPaymentTrackerGroup")||func.equals("getReservationAllPaymentTrackerSingle")
					||func.equals("getReservationNoShow")||func.equals("getReservationNoShowGroup")||func.equals("getReservationNoShowSingle")
					||func.equals("getReservationAllCancelResv")||func.equals("getReservationAllCancelResvGroup")||func.equals("getReservationAllCancelResvSingle")
					||func.equals("getReservationAllTemp")||func.equals("getReservationAllTempGroup")||func.equals("getReservationAllTempSingle")
					||func.equals("getReservationBookingDeposits")||func.equals("getReservationBookingDepositsGroup")||func.equals("getReservationBookingDepositsSingle")
					||func.equals("getReservationAllCheckinPendingOnly")||func.equals("getReservationAllCheckinPendingOnlyGroup")||func.equals("getReservationAllCheckinPendingOnlySingle")
					||func.equals("getReservationAll")||func.equals("getReservationAllGroup")||func.equals("getReservationAllSingle")
					||func.equals("getReservationAllCheckoutPending")||func.equals("getReservationAllCheckoutPendingGroup")||func.equals("getReservationAllCheckoutPendingSingle")) {
				GetReservationAll(req, resp);
			}
			else if (func.equals("getReservationAllPoint")) {
				GetReservationAllCount(req, resp);
			}
			else if (func.equals("getGroup")) {
				GetGroup(req, resp);
			}
			else if (func.equals("getReservationAllCheckin")) {
				GetReservationAllCheckin(req, resp);
			}
			else if (func.equals("editReservationGroupCheckin")){
				EditReservationGroupCheckin( req, resp);
			}
			else if (func.equals("getReservationAllCheckout")){
				GetReservationAllCheckout( req, resp);
			}
			else if (func.equals("getReservationStatusCheck")) {
				GetResavetionStatusCheck(req, resp);
			}
			else if (func.equals("getReservationGroup")) {
				GetGroupResavetionStatusCheck(req, resp);
			}
			else if (func.equals("loadBookingDetail")) {
				LoadBookingDetail(req, resp);
			}
			else if(func.equals("loadGuestList")){
				LoadGuestList(req, resp);
			}
			else if(func.equals("insertGuest")){
				InsertGuest(req, resp);
			}
			else if(func.equals("removeGuestFormRes")){
				RemoveGuestFormRes(req, resp);
			}
			else if(func.equals("editCharge")){
				EditCharge(req, resp);
			}
			else if(func.equals("addReservationStatus")){
				AddReservationStatus(req, resp);
			}
			else if(func.equals("editChargeGroup")){
				EditChargeGroup(req, resp);
			}
			else if(func.equals("addResFromEmpty")){
				AddResFromEmpty1(hotelId,req, resp);
			}
			else if(func.equals("assignRoom")){
				AssignRoom(req, resp);
			}
			else if(func.equals("EditRoomSubReservation")){
				EditRoomSubReservation(req,resp);
			}
			else if(func.equals("getGuest")){
				GetGuestForFrontPage(req, resp);
			}
			else if(func.equals("getReservationInGroup")){
				GetReservationInGroup(req, resp);
			}
			else if(func.equals("clearGuest")){
				ClearGuest(req,resp);
			}
			else if(func.equals("createGuestSingleInGroup")){
				CreateGuestSingleInGroup(req,resp);
			}
			else if(func.equals("createGroupRoomManage")){
				CreateGroupRoomManage(req,resp);
			}
			else if(func.equals("removeFromGroupRoomManage")){
				RemoveFromGroupRoomManage(req,resp);
			}
			else if(func.equals("addFromGroupRoomManage")){
				AddFromGroupRoomManage(req,resp);
			}
			else if(func.equals("createGroupandAddRes")){
				CreateGroupandAddRes(req,resp);
			}
			else if(func.equals("changeTempToReservatonRoomManage")){
				ChangeTempToReservatonRoomManage(req,resp);
			}
			else if(func.equals("exportFile")){
				ExprotFile(req,resp);
			}
			else if(func.equals("CheckInResvList")){
				CheckInResvList(req,resp);
			}
			else if(func.equals("EditResvListCheckInCheckOut")){
				EditResvListCheckInCheckOut(req,resp);
			}
			else if(func.equals("InsertGuestResInGroup"))
			{
				InsertGuestResInGroup(req,resp);
			}
			else if(func.equals("IncreaseReservation"))
				IncreaseReservation(req,resp);
			else if(func.equals("testLogicReservation"))
				testLogicReservation(req,resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void GetReservationList(long hotelId, HttpServletRequest req,
			HttpServletResponse resp) throws IOException, ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Date date = formatter.parse(req.getParameter("date"));
		long span = 0;
		if (req.getParameter("span") == "" || req.getParameter("span") == "0") {
			span = 1;
		} else {
			span = Long.parseLong(req.getParameter("span"));
		}

		DNRLogic dnrLogic = new DNRLogic(req,resp);
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		RoomLogic roomLogic = new RoomLogic(req,resp);
		List<ReservationData> reservationData = resLogic.GetReservationListWithoutCancel(hotelId, date, span);
		List<DNR> dnrList = dnrLogic.GetReservationList(hotelId, date, span);
		for(DNR dnr:dnrList){
			ReservationData resData = dnrLogic.DNRtoReservationData(dnr);
			resData = resLogic.TrimReservationToSpanDate(resData,date,span);
			if(resData.getSpan()>0)
				reservationData.add(resData);
		}
		List<HashMap<String,Object>> hash = new ArrayList<HashMap<String,Object>>();
		for(ReservationData resData:reservationData)
			hash.add(resLogic.MinReservationData(resData));

		List<HashMap<String,Object>> roomStatus = new ArrayList<HashMap<String,Object>>();
		List<Room> rooms = roomLogic.GetRoomWithCache(hotelId);
		for(Room room : rooms){
			HashMap<String,Object> item = new HashMap<String,Object>();
			item.put("rm", room.getId());
			item.put("s", Long.parseLong(room.getCleaningStatusString()));
			roomStatus.add(item);
		}		
		HashMap<String,Object> rs = new HashMap<String,Object>();
		rs.put("ResLst", hash);
		rs.put("Cs", roomStatus);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rs));
	}

	private void LoadGroup(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ParseException {

		long groupId = Long.parseLong(req.getParameter("groupId"));

		ReservationLogic resLogic = new ReservationLogic(req,resp);
		Group g = resLogic.GetGroup(groupId);
		Gson gson = new Gson();
		HashMap<String , Object> hash=Util.toHashmapformfield(g);
		hash.put("lateCheckout",new ChargeLogic(req,resp).CheckChargeInUse(g.getOtherChargeString(),"LateCheckout"));
		hash.put("GroupStatus", resLogic.LoadBookingDetail(groupId,false));
		hash.put("GroupcheckStauts",resLogic.LoadBookingDetail(groupId,true));
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(hash));
	}

	private void CreateReservation(long hotelId, HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		Gson gson = new Gson();
		try {
			String sessionCheck = Util.checkSessionEntity(req,resp);
			if(sessionCheck==null||sessionCheck.equals("")){
				resp.setContentType("text/plain; charset=UTF-8");
				resp.getWriter().println(gson.toJson(new ResultData(false)));
				return;
			}
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
					Locale.ENGLISH);
			Date date = formatter.parse(req.getParameter("date"));
			long span = Long.parseLong(req.getParameter("span"));
			String roomId = req.getParameter("rmId");
			String roomType = req.getParameter("rmType");
			long roomAmount = Long.parseLong(req.getParameter("roomamount"));
			String priceRateId = req.getParameter("priceRate");
			long adult = Long.parseLong(req.getParameter("adult"));
			long child = Long.parseLong(req.getParameter("child"));
			boolean isAssign = Boolean.parseBoolean(req.getParameter("isA"));
			GenericLogic generalLogic = new GenericLogic(req,resp);
			ReservationStatus rsv = generalLogic.GetReservationStatus(hotelId,
					req.getParameter("ReservationStatus"));
			String reservationStatus  = Long.toString(rsv.getId());
			String GuestId = req.getParameter("guest");

			long salutatinId = Long.parseLong(req.getParameter("sal"));
			String name = req.getParameter("nm");
			String lastName = req.getParameter("lsNm");
			String phone = req.getParameter("phone");
			String mail = req.getParameter("mail");
			Double pay = Double.parseDouble(req.getParameter("pay"));

			String sources = "";
			String reason  = "";
			long extrabed   = 0;
			RoomTypeLogic rmLogic = new RoomTypeLogic(req,resp);
			RoomType rmData = rmLogic.GetRoomType(Long.parseLong(roomType));
			if ((child + adult) - (long) rmData.getStandardOccupancy() >= 0) {
				extrabed = (child + adult) - rmData.getStandardOccupancy();
			} else {
				extrabed = 0;
			}
			String agencyId = "";
			if (req.getParameter("agencyId").equals("0")) {
				AgencyLogic aLogic = new AgencyLogic(req,resp);
				long displayID = aLogic.GetMaxAgentDisplayId(hotelId);
				Agency agent = aLogic.AddAgency(hotelId,
						req.getParameter("agency"), "",(displayID+1));
				agencyId = String.valueOf(agent.getId());
			} else {
				agencyId = req.getParameter("agencyId");
			}
			String guestnamelist = req.getParameter("arrayguestname");
			String guestsolutationlist = req.getParameter("arrayguestsolutation");
			String guestlastnamelist = req.getParameter("arrayguestlastname");
			String guestphonelist = req.getParameter("arrayguestphone");
			String guestemaillist = req.getParameter("arrayguestemail");
			GuestLogic guestLogic = new GuestLogic(req,resp);
			ReservationLogic reservationLogic = new ReservationLogic(req,resp);
			String gsId = (GuestId.equals("0"))? String.valueOf(guestLogic.AddGuest(salutatinId, name, lastName,
						phone,  mail).getId()) : GuestId;
			Reservation rse = reservationLogic.CreateReservation(hotelId,
					date, span, roomId, roomType, priceRateId, adult,
					child, isAssign, gsId,
					reservationStatus, roomAmount, sources,
					extrabed, reason, agencyId, pay,guestnamelist,guestsolutationlist,
					guestlastnamelist,guestphonelist,guestemaillist);
			long groupId=0;
			if(roomAmount>1){
				groupId=rse.getGroupIdNumber();
			}
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultCreResData(true,groupId)));
		} catch (Exception e) {
			resp.getWriter().println(gson.toJson(new ResultCreResData(false,0)));
		}

	}
	
	private void CreateGroupRoomManage(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		
		String resId = req.getParameter("resId");
		Date date = formatter.parse(req.getParameter("date"));
		long span = Long.parseLong(req.getParameter("span"));
		String roomType = req.getParameter("rmType");
		String priceRateId = req.getParameter("priceRate");
		Double pay = Double.parseDouble(req.getParameter("pay"));
		long salutationGuestGroup = Long.parseLong(req.getParameter("salutation"));
		String nameGusetGroup = req.getParameter("nameguestGroup");
		String lastnameGusetGroup = req.getParameter("lastnameguestGroup");
		String tellGusetGroup = req.getParameter("tellgusetGroup");
		String reason = req.getParameter("reason");
		String source = req.getParameter("source");
		String note = req.getParameter("note");
		String agencyId =  req.getParameter("agency");
		String company = req.getParameter("company");
		long extrabed = Long.parseLong(req.getParameter("extrabed"));
		AgencyLogic aLogic = new AgencyLogic(req,resp);
		long displayID = aLogic.GetMaxAgentDisplayId(hotelId);
		Agency agent = aLogic.AddAgency(hotelId,agencyId,company,(displayID+1));
		agencyId = String.valueOf(agent.getId());
		GuestLogic guestLogic = new GuestLogic(req,resp);
		String mail = "";
		Guest gs = guestLogic.AddGuest(salutationGuestGroup, nameGusetGroup, lastnameGusetGroup,
				tellGusetGroup, mail);
		long gusetGroupId = gs.getId();
		ReservationLogic reservationLogic = new ReservationLogic(req,resp);
		Group g =  reservationLogic.CreateGroup(req,resp,hotelId,date,span,roomType,priceRateId,pay,
				gusetGroupId, reason, source, note, extrabed, "0", "0");
		resp.setContentType("text/plain; charset=UTF-8");
		if (g != null) {
			reservationLogic.EditGroupRoomManage(hotelId, g.getId(), resId,agencyId);
			List<ReservationDataForReport> gg = reservationLogic.GetReservationAllReportRoomManage(hotelId,g.getId());
			resp.getWriter().println(gson.toJson(gg));
		} else {
			resp.getWriter().println(gson.toJson(false));
		}
	}
	private void RemoveFromGroupRoomManage(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException, JSONException {
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		
		String dataGroup  = req.getParameter("dataArray");
		String[] dataArray = dataGroup.split("_");
		List<List<ReservationDataForReport>> gg = new ArrayList<List<ReservationDataForReport>>();
		ReservationLogic reservationLogic = new ReservationLogic(req,resp);
		for(int i = 0;i<dataArray.length;i++){
			JSONObject obj = new JSONObject(dataArray[i]);
			long groupId = Long.parseLong(obj.getString("groupId"));
			String resIds = obj.getString("subRes");
			Group g = reservationLogic.RemoveFromGroupRoomManage(hotelId,groupId,resIds);
			gg.add(reservationLogic.GetReservationAllReportRoomManage(hotelId,g.getId()));
		}
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(gg));
	}
	
	private void ChangeTempToReservatonRoomManage(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException, JSONException {
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		String resId = req.getParameter("resId");
		String resStatus = req.getParameter("reservationstatus");
		boolean sellRoom = Boolean.parseBoolean(req.getParameter("sellroom"));
		boolean isAssign = Boolean.parseBoolean(req.getParameter("isassign"));
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm",
				Locale.ENGLISH);
		Date dateCheckin = formatter.parse(req.getParameter("dateCheckin"));
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		Reservation res = resLogic.EditReservation(hotelId, Long.parseLong(resId), resStatus, sellRoom,
				isAssign, dateCheckin);
		ReservationDataForReport r = resLogic.GetReservationRoomManage(hotelId,res.getId());
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(r));
	}
	
	private void AddFromGroupRoomManage(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException, JSONException {
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		String dataGroup  = req.getParameter("dataArray");
		ReservationLogic reservationLogic = new ReservationLogic(req,resp);
		List<List<ReservationDataForReport>> gg = new ArrayList<List<ReservationDataForReport>>();
		JSONObject obj = new JSONObject(dataGroup);
		long groupId = Long.parseLong(obj.getString("groupId"));
		String resIds = obj.getString("subRes");
		Group g = reservationLogic.AddFromGroupRoomManage(hotelId,groupId,resIds);
		gg.add(reservationLogic.GetReservationAllReportRoomManage(hotelId,g.getId()));
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(gg));
	}

	private void EditAfterReservation(long hotelId, HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String resId = req.getParameter("resId");
		String resStatus = req.getParameter("reservationstatus");
		boolean sellRoom = Boolean.parseBoolean(req.getParameter("sellroom"));
		boolean isAssign = Boolean.parseBoolean(req.getParameter("isassign"));
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm",
				Locale.ENGLISH);
		Date dateCheckin = formatter.parse(req.getParameter("dateCheckin"));
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		String [] resIdList = resId.trim().split(",");
		if(resIdList.length>1)
		{
		List<Reservation> list = new ArrayList<Reservation>();
			for(int i=0;i<resIdList.length;i++)
			{
				Reservation res = resLogic.EditReservation(hotelId, Long.parseLong(resIdList[i]), resStatus, sellRoom,
						isAssign, dateCheckin);
				list.add(res);
			}
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(list));
		}else
		{
			Reservation res = resLogic.EditReservation(hotelId, Long.parseLong(resId), resStatus, sellRoom,
					isAssign, dateCheckin);
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(res));
		}
	}

	private void EditNote(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		Group g= new Group();
		Reservation r = new Reservation();
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		long id = 0;
		String note = req.getParameter("note");
		if (!String.valueOf(req.getParameter("groupId")).equals("0")) {
			id = Long.parseLong(req.getParameter("groupId"));
			g=resLogic.SaveNote(hotelId, id, note);
			g.getNote();
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(g.getNote()));
			
		} else {
			id = Long.parseLong(req.getParameter("resId"));
			r=resLogic.SaveNoteS(hotelId, id, note);
			r.getNote();
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(r.getNote()));
		}
	}

	private void EditGuestData(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long resId =Long.parseLong(req.getParameter("resId"));
		 String Name =req.getParameter("Name");
		 String lastName =req.getParameter("lastName");
		 String SName =req.getParameter("SName");
		 String mail=req.getParameter("mail");
		 String gender=req.getParameter("gender");
		 String birthday=req.getParameter("birthday");
		 String nationalityString=req.getParameter("nationalityString");
		 String phone=req.getParameter("phone");
		 String	idNumber=req.getParameter("idNumber");
		 String passportNumber=req.getParameter("passportNumber");
		 String driverlicense=req.getParameter("driverlicense");
		 String socialSecuritycard=req.getParameter("socialSecuritycard");
		 String addressLine=req.getParameter("addressLine");
		 String country=req.getParameter("country");
		 String state=req.getParameter("state");
		 String city=req.getParameter("city");
		 String pincode=req.getParameter("pincode");
		 String fax=req.getParameter("fax");
		 String	designation=req.getParameter("designation"); 
		 String company=req.getParameter("company");
		 String officeAddress=req.getParameter("officeAddress");
		 String officeCountry=req.getParameter("officeCountry");
		 String officeState=req.getParameter("officeState");
		 String officeCity=req.getParameter("officeCity");
		 String officePincode=req.getParameter("officePincode");
		 String officePhone=req.getParameter("officePhone");
		 String officeFax=req.getParameter("officeFax");
		 String officeEmail=req.getParameter("officeEmail");
		 boolean isVIP=Boolean.parseBoolean(req.getParameter("isVIP"));
		 boolean isBlackList=Boolean.parseBoolean(req.getParameter("isBlackList"));
		 String note=req.getParameter("note");
		long guestId = Long.parseLong(req.getParameter("guestId"));
		
		Guest guest = new GuestLogic(req,resp).EditGuestData(hotelId,Name,lastName,SName,mail,gender,birthday,nationalityString
				,phone,idNumber,passportNumber,driverlicense,socialSecuritycard
				,addressLine,country,state,city,pincode,fax,company
				,officeAddress,officeCountry,officeState,officeCity,officePincode,officePhone
				,officeFax,officeEmail,isVIP,isBlackList,note,guestId,designation);
		
		ReservationLogic resLogic = new ReservationLogic(req, resp);
		Reservation rsv = resLogic.GetReservation(resId);
		rsv.setGuestString(String.valueOf(guest.getId()));
		rsv.setAdditionalGuestString(String.valueOf(guest.getId()));
		resLogic.UpdateReservation(rsv);
		
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(guest));
	}

	private void RemoveResFormDatastore(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		long res = Long.parseLong(req.getParameter("resId"));
		ReservationLogic reservationLogic = new ReservationLogic(req,resp);
		boolean s = reservationLogic.RemoveRes(res);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(s));
	}
	
	private void RemoveResTempFormDatastore(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		long hotelId = 1;
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		long res = Long.parseLong(req.getParameter("resId"));
		long groupId =Long.parseLong(req.getParameter("groupId"));
		String checkType = req.getParameter("type");
		ReservationLogic reservationLogic = new ReservationLogic(req,resp);
		Reservation r = reservationLogic.GetReservation(Long.parseLong(req.getParameter("resId")));
		String listPaymentId = r.getPaymentListString();
		String[] listPaymentArray = listPaymentId.split(",");
		String newlistResv = "";
		PaymentLogic p = new PaymentLogic(req,resp);
		if(checkType.equals("Group")){
			Group gg = reservationLogic.GetGroup(Long.parseLong(req.getParameter("groupId")));
			String listPaymentIdGroup = gg.getPaymentListString();
			String[] listPaymentGroupArray = listPaymentIdGroup.split(",");
			Group g = reservationLogic.GetGroup(groupId);
			String[] resList = g.getListResvString().split(",");
			for(int i = 0;i<resList.length;i++){
				if(!resList[i].trim().equals(req.getParameter("resId"))){
					newlistResv += resList[i].trim()+",";
				}
			}
			if(newlistResv.equals("")){
				for(int i =0;i<listPaymentGroupArray.length;i++){
					p.RemovePayment(Long.parseLong(listPaymentGroupArray[i]));
				}
			}
			if(newlistResv.length()!=0){
				newlistResv = newlistResv.substring(0,newlistResv.length()-1).trim();
			}else{
				newlistResv = "0";
			}
			reservationLogic.EditGroupRoomManage(hotelId,groupId,newlistResv,g.getListResv().get(0).getAgencyIdString());
			boolean s = reservationLogic.RemoveRes(res);
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(s));
		}else{
			if(!listPaymentArray[0].equals("")){
				for(int i =0;i<listPaymentArray.length;i++){
					p.RemovePayment(Long.parseLong(listPaymentArray[i]));
				}
			}
			boolean s = reservationLogic.RemoveRes(res);
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(s));
		}
	}

	private void LoadGroupResvList(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, ParseException {
		String groupId = req.getParameter("groupId");
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		Group g = resLogic.GetGroup(Long.parseLong(groupId));
		List<Reservation> list = g.getListResv();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).isAvaliable() == false) {
				list.remove(i);
				i = 0;
			}
		}
		List<ReservationDataFullWithTask> resvfull = new ArrayList<ReservationDataFullWithTask>();
		for(int i = 0;i< list.size();i++){
			ReservationDataFullWithTask datafull =  resLogic.FillReservationDataFullWithTask(list.get(i));
			resvfull.add(datafull);
		}
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(resvfull));
	}
	private void LoadGroupResvListCancel(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, ParseException {
		String groupId = req.getParameter("groupId");

		Group g = new ReservationLogic(req,resp).GetGroup(Long.parseLong(groupId));
		List<Reservation> list = g.getListResv();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).isAvaliable() == true) {
				list.remove(i);
				i = 0;
			}
		}
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(list));
	}

	// //GET ID TASK LIST :: Reservation
	private void GetIdTaskList(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ParseException {
		Long res_id = Long.parseLong(req.getParameter("res_id"));
		Reservation id_taskList = new ReservationLogic(req,resp).GetIdTaskList(res_id);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(id_taskList));
	}

	private void GetIdTaskListGroup(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, ParseException {
		Long group_id = Long.parseLong(req.getParameter("group_id"));
		Group id_taskList = new ReservationLogic(req,resp).GetIdTaskListGroup(group_id);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(id_taskList));
	}

	private void EditDetailGroup(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		Gson gson = new Gson();
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long groupId = Long.parseLong(req.getParameter("groupId"));
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Date date = formatter.parse(req.getParameter("date"));
		long extrabed = Long.parseLong(req.getParameter("extrabed"));
		String reason = req.getParameter("reason");
		String source = req.getParameter("source");
		date = new Date(date.getTime());
		long span = Long.parseLong(req.getParameter("span"));
		

		ReservationLogic rLogic = new ReservationLogic(req,resp);
		Group g = rLogic.EditDetailGroup(hotelId, groupId, date, extrabed,
				reason, source, span);
		boolean z;
		if (g != null) {
			z = true;
		} else {
			z = false;
		}
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(z));
	}
	
	private void EditDetailReservation(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long resId = Long.parseLong(req.getParameter("resId"));
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Date date = formatter.parse(req.getParameter("date"));
		long extrabed = Long.parseLong(req.getParameter("extrabed"));
		String reason = req.getParameter("reason");
		String source = req.getParameter("source");
		long span = Long.parseLong(req.getParameter("span"));
		HashMap<String, Object> obj = new ReservationLogic(req,resp).EditAboutDetailReservation(hotelId,resId,date,extrabed,reason,source,span);
		
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}

	private void EditNameS(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		String name = req.getParameter("name");
		String lastName = req.getParameter("lastname");
		Long resvId = Long.parseLong(req.getParameter("resvId"));
		GuestLogic guestLogic = new GuestLogic(req,resp);
		Guest g = guestLogic.AddGuest(0, name, lastName, "", "");
		ReservationLogic rLogic = new ReservationLogic(req,resp);
		Reservation r = rLogic.EditGuest(resvId, String.valueOf(g.getId()));
		Gson gson = new Gson();
		boolean z = false;
		if (g != null || r != null) {
			z = true;
		}
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(z));
	}
	
	private void EditRoomtypeS(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		Gson gson = new Gson();
		long resvId = Long.parseLong(req.getParameter("resvId"));
		String roomtypeId = req.getParameter("roomtypeId");
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		Reservation g = gLogic.EditRoomtypeS(resvId, roomtypeId);
		resp.setContentType("text/plain; charset=UTF-8");
		if (g != null) {
			resp.getWriter().println(gson.toJson(true));
		} else {
			resp.getWriter().println(gson.toJson(false));
		}

	}

	private void EditRoomSubReservation(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		long resvId = Long.parseLong(req.getParameter("resvId"));
		long roomId = Long.parseLong(req.getParameter("roomId"));
		String isAssign = req.getParameter("isAssign");
		long min = 0;
		if(req.getParameter("min") != null && req.getParameter("min") != "")
			min = Long.parseLong(req.getParameter("min"));
		boolean withAssign = (isAssign != null && isAssign.equals("true"))? true:false;
		long span = 0;//Long.parseLong(req.getParameter("span"));
//			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
//					Locale.ENGLISH);
		Date date = new Date();//formatter.parse(req.getParameter("date"));
		
		ReservationLogic resvLogic = new ReservationLogic(req,resp);
		SubReservationLogic subResvLogic = new SubReservationLogic(req,resp);
		
		Reservation res;
		SubReservation subRes = null;
		res = resvLogic.GetReservation(resvId);
		if(res == null)
			subRes = subResvLogic.GetSubReservation(resvId);
		
		boolean canMove = false;
		long fromRoom;
		if(res == null)
		{
			canMove = resvLogic.CanBeMoveToRoom(subRes,roomId);
			span = subRes.getSpan();
			date = subRes.getDate();
			fromRoom = subRes.getRoom().getId();
		}
		else
		{
			canMove = resvLogic.CanBeMoveToRoom(res,roomId);
			span = res.getSpan();
			date = res.getDate();
			fromRoom = res.getRoom().getId();
		}
		//boolean canMove = resvLogic.CanBeMoveToRoom(subResvLogic.GetSubReservation(resvId), roomId);
		List<EffectedRoom> effectedlist = new ArrayList<EffectedRoom>();
		
		HashMap<String,Object> hashmap = new HashMap<String,Object>();
		
		List<Charge> chargeList = new ArrayList<Charge>();
		if(canMove)
		{
			long order = 0;
			List<SubReservation> list = resvLogic.GetReservationWithinDateInSpecificRoom(hotelId,date,span,roomId);
			for(SubReservation s : list)
			{
				Reservation parent = s.getParent();
				Date chkDateTo = (res == null)? subRes.getDateTo() : res.getDateTo();
				if(date.equals(Util.addDays(chkDateTo,-1)) && s.isSellRoom())
				{
					if(order < parent.getOrder()) order = parent.getOrder();
				}
				else{
					Room r = resvLogic.AutoMoveRoom(s,fromRoom);
					long id = (s.getId() > 0)? s.getId():s.getParentId();
					effectedlist.add(new EffectedRoom(id,r.getId()));
				}
			}

			RoomLogic roomLogic = new RoomLogic(req,resp);
			Room room = roomLogic.GetRoom(roomId);
			if(res == null)
			{
				subRes.setRoom(room);
				subRes.setRoomType(room.getRoomtype());
				
				effectedlist.add(new EffectedRoom(subRes.getId(),room.getId()));
				
				subResvLogic.UpdateSubReservation(subRes);
				
				Reservation tmpRes = resvLogic.GetReservation(subRes.getParentId());
				chargeList = new ChargeLogic(req,resp).CalCharge(hotelId,tmpRes.getSubReservationList(),tmpRes.getPackageByDate(),tmpRes.getDate(),tmpRes.getDateTo());
			}
			else
			{
				res.setOrder(order + 1);
				res.setRoom(room);
				res.setRoomType(room.getRoomtype());
				if(withAssign)
					res.setAssign(true);

				effectedlist.add(new EffectedRoom(res.getId(),room.getId()));
				
				resvLogic.UpdateReservation(res);
				
				SubReservation tmpSubRes = new SubReservation();
				tmpSubRes.CloneReservation(res);
				chargeList = new ChargeLogic(req,resp).CalCharge(hotelId,Arrays.asList(tmpSubRes),res.getPackageByDate(),res.getDate(),res.getDateTo());
			}
		}
		hashmap.put("EffectedRoom", effectedlist);
		if(min==0) hashmap.put("ChargeList", chargeList);
		
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(hashmap));
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void EditRoomS(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		Gson gson = new Gson();
		HttpSession session = req.getSession(true);
		long hotelId = (Long) session.getAttribute("hotelId");
		long resvId = Long.parseLong(req.getParameter("resvId"));
		long roomId = Long.parseLong(req.getParameter("roomId"));
		long roomType = Long.parseLong(req.getParameter("roomtype"));
		long span = Long.parseLong(req.getParameter("span"));
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Date date = formatter.parse(req.getParameter("date"));
		long dateStart =date.getTime(); 
		long dateEnd = date.getTime() + span * 24 * 60 *60*1000;
		
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		
		List<Reservation> rsvLastOne = gLogic.GetRoomUsedBetweenCheckin(hotelId,date,roomType,roomId);
		long lastOneEnd = rsvLastOne.get(0).getDate().getTime() + (rsvLastOne.get(0).getSpan() * 24 * 60 * 60 * 1000);
		
		List<Reservation> rsvFirstOne = gLogic.GetRoomUsedBetweenCheckout(hotelId,date,roomType,roomId);
		long firstOneStart =0;
		if(rsvFirstOne.size() != 0){
			 firstOneStart = rsvFirstOne.get(0).getDate().getTime() ;
		}else{
			 firstOneStart = date.getTime() + (span+1) * 24 * 60 *60*1000 ;
		}
		
		
		boolean g = false;
		if(lastOneEnd <= dateStart && firstOneStart >= dateEnd){
			gLogic.EditRoomS2(resvId, String.valueOf(roomId));
			g = true;
		}else if(lastOneEnd >= dateStart && firstOneStart >= dateEnd){
			if(!rsvLastOne.get(0).isAssign()){
				Date lastOneDate = rsvLastOne.get(0).getDate();
				Date cDate =new Date( lastOneDate.getTime()+ ((rsvLastOne.get(0).getSpan() - 1) * 24 * 60 * 60 * 1000));
				List<Reservation> rsv = new ReservationLogic(req,resp).GetRoomUsed(hotelId,cDate,rsvLastOne.get(0).getRoomType().getId());
				String[] t = new String[rsv.size()];
				List<String> roomIdList ;
				Set<String> set = null;
				if (rsv.size() != 0) {
					for (int i = 0; i < rsv.size(); i++) {
						if ((rsv.get(i).getDate().getTime() + (rsv.get(i).getSpan() * 24 * 60 * 60 * 1000)) > lastOneDate
								.getTime()) {
							t[i] = String.valueOf(rsv.get(i).getRoom().getId());
						}
					}
					roomIdList = Arrays.asList(t);
					set = new HashSet(roomIdList);
					set.remove(null);
					List<Long> x = new ArrayList(set);
					List<Room> room = new RoomLogic(req,resp).GetRoomWithCache(hotelId, roomType);
					long[] roomInt = new long[room.size()];
					for(int i=0;i<room.size();i++){
						roomInt[i] = room.get(i).getId();
					}
					List<Long> roomIntList = new ArrayList(Arrays.asList(roomInt));
					for(int i =0;i<x.size();i++){
						for(int k=0;k<roomIntList.size();k++){
							if(String.valueOf(x.get(i)).equals(String.valueOf(roomIntList.get(k))) ){
								roomIntList.remove(k);
								break;
							}
						}
					}	
					if(roomIntList != null && roomIntList.size() !=0){
						gLogic.EditRoomS(rsvLastOne.get(0).getId(), String.valueOf(roomIntList.get(0)));
						gLogic.EditRoomS2(resvId, String.valueOf(roomId));
						g= true;
					}else{
						g= false;
					}
				}
			}
		}else if(lastOneEnd <= dateStart && firstOneStart <= dateEnd){
			if(rsvFirstOne.size() != 0){
				if(!rsvFirstOne.get(0).isAssign()){
					Date firstOneDate = rsvFirstOne.get(0).getDate();
					Date cDate =new Date( firstOneDate.getTime()+ ((rsvFirstOne.get(0).getSpan() - 1) * 24 * 60 * 60 * 1000));
					List<Reservation> rsv = new ReservationLogic(req,resp).GetRoomUsed(hotelId,cDate, rsvFirstOne.get(0).getRoomType().getId());
					String[] t = new String[rsv.size()];
					List<String> roomIdList ;
					Set<String> set = null;
					if (rsv.size() != 0) {
						for (int i = 0; i < rsv.size(); i++) {
							if ((rsv.get(i).getDate().getTime() + (rsv.get(i).getSpan() * 24 * 60 * 60 * 1000)) > firstOneDate
									.getTime()) {
								t[i] = String.valueOf(rsv.get(i).getRoom().getId());
							}
						}
						roomIdList = Arrays.asList(t);
						set = new HashSet(roomIdList);
						set.remove(null);
						List<Long> x = new ArrayList(set);
						List<Room> room = new RoomLogic(req,resp).GetRoom(hotelId, roomType);
						long[] roomInt = new long[room.size()];
						for(int i=0;i<room.size();i++){
							roomInt[i] = room.get(i).getId();
						}
						List<Long> roomIntList = new ArrayList(Arrays.asList(roomInt));
						for(int i =0;i<x.size();i++){
							for(int k=0;k<roomIntList.size();k++){
								if(String.valueOf(x.get(i)).equals(String.valueOf(roomIntList.get(k))) ){
									roomIntList.remove(k);
									break;
								}
							}
						}	
						if(roomIntList != null && roomIntList.size() !=0){
							gLogic.EditRoomS(rsvFirstOne.get(0).getId(), String.valueOf(roomIntList.get(0)));
							gLogic.EditRoomS2(resvId, String.valueOf(roomId));
							g= true;
						}else{
							g= false;
						}
					}
				}
			}else{
				gLogic.EditRoomS2(resvId, String.valueOf(roomId));
				g= true;
			}
			
		}else if(lastOneEnd >= dateStart && firstOneStart <= dateEnd){
			if(rsvFirstOne.size() != 0){
				if(!rsvLastOne.get(0).isAssign() && !rsvFirstOne.get(0).isAssign()){
					Date firstOneDate = rsvFirstOne.get(0).getDate();
					Date cDate =new Date( firstOneDate.getTime()+ ((rsvFirstOne.get(0).getSpan() - 1) * 24 * 60 * 60 * 1000));
					List<Reservation> rsv = new ReservationLogic(req,resp).GetRoomUsed(hotelId,cDate,rsvFirstOne.get(0).getRoomType().getId());
					String[] t = new String[rsv.size()];
					List<String> roomIdList ;
					Set<String> set = null;
					if (rsv.size() != 0) {
						for (int i = 0; i < rsv.size(); i++) {
							if ((rsv.get(i).getDate().getTime() + (rsv.get(i).getSpan() * 24 * 60 * 60 * 1000)) > firstOneDate
									.getTime()) {
								t[i] = String.valueOf(rsv.get(i).getRoom().getId());
							}
						}
					}
						roomIdList = Arrays.asList(t);
						set = new HashSet(roomIdList);
						set.remove(null);
						List<Long> x = new ArrayList(set);
						List<Room> room = new RoomLogic(req,resp).GetRoom(hotelId, roomType);
						long[] roomInt = new long[room.size()];
						for(int i=0;i<room.size();i++){
							roomInt[i] = room.get(i).getId();
						}
						List<Long> roomIntList = new ArrayList(Arrays.asList(roomInt));
						for(int i =0;i<x.size();i++){
							for(int k=0;k<roomIntList.size();k++){
								if(String.valueOf(x.get(i)).equals(String.valueOf(roomIntList.get(k))) ){
									roomIntList.remove(k);
									break;
								}
							}
						}
					
					Date lastOneDate = rsvLastOne.get(0).getDate();
					Date aDate =new Date( lastOneDate.getTime()+ ((rsvLastOne.get(0).getSpan() - 1) * 24 * 60 * 60 * 1000));
					List<Reservation> rsv2 = new ReservationLogic(req,resp).GetRoomUsed(hotelId,aDate,rsvLastOne.get(0).getRoomType().getId());
					String[] t2 = new String[rsv2.size()];
					List<String> roomIdList2 ;
					Set<String> set2 = null;
					if (rsv2.size() != 0) {
						for (int i = 0; i < rsv2.size(); i++) {
							if ((rsv2.get(i).getDate().getTime() + (rsv2.get(i).getSpan() * 24 * 60 * 60 * 1000)) > firstOneDate
									.getTime()) {
								t[i] = String.valueOf(rsv2.get(i).getRoom().getId());
							}
						}				
						roomIdList2 = Arrays.asList(t2);
						set2 = new HashSet(roomIdList2);
						set2.remove(null);
						List<Long> y = new ArrayList(set);
						List<Room> room2 = new RoomLogic(req,resp).GetRoom(hotelId, roomType);
						long[] roomInt2 = new long[room.size()];
						for(int i=0;i<room2.size();i++){
							roomInt2[i] = room2.get(i).getId();
						}
						List<Long> roomIntList2 = new ArrayList(Arrays.asList(roomInt2));
						for(int i =0;i<y.size();i++){
							for(int k=0;k<roomIntList2.size();k++){
								if(String.valueOf(y.get(i)).equals(String.valueOf(roomIntList2.get(k))) ){
									roomIntList2.remove(k);
									break;
								}
							}
						}	
						
						if(roomIntList != null && roomIntList.size() !=0 && roomIntList2 != null && roomIntList2.size() !=0){
							gLogic.EditRoomS(rsvFirstOne.get(0).getId(), String.valueOf(roomIntList.get(0)));
							gLogic.EditRoomS(rsvLastOne.get(0).getId(), String.valueOf(roomIntList2.get(0)));
							gLogic.EditRoomS2(resvId, String.valueOf(roomId));
							g= true;
						}else{
							g= false;
						}
					}
			}
			}else{
				if(!rsvLastOne.get(0).isAssign() ){
					Date firstOneDate = formatter.parse(String.valueOf(rsvFirstOne.get(0).getDate()));
					Date cDate =new Date( firstOneDate.getTime()+ ((rsvFirstOne.get(0).getSpan() - 1) * 24 * 60 * 60 * 1000));
					List<Reservation> rsv = new ReservationLogic(req,resp).GetRoomUsed(hotelId,cDate, rsvFirstOne.get(0).getRoomType().getId());
					String[] t = new String[rsv.size()];
					List<String> roomIdList ;
					Set<String> set = null;
					if (rsv.size() != 0) {
						for (int i = 0; i < rsv.size(); i++) {
							if ((rsv.get(i).getDate().getTime() + (rsv.get(i).getSpan() * 24 * 60 * 60 * 1000)) > firstOneDate
									.getTime()) {
								t[i] = String.valueOf(rsv.get(i).getRoom().getId());
							}
						}
					}
						roomIdList = Arrays.asList(t);
						set = new HashSet(roomIdList);
						set.remove(null);
						List<Long> x = new ArrayList(set);

						if(x != null && x.size() !=0){
							gLogic.EditRoomS(rsvFirstOne.get(0).getId(), String.valueOf(x.get(0)));
							gLogic.EditRoomS2(resvId, String.valueOf(roomId));
							g= true;
						}else{
							g= false;
						}
					}
			}
			}
			
		resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(g));
	}
	private void EditRoomStatusS(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		Gson gson = new Gson();
		long resvId = Long.parseLong(req.getParameter("resvId"));
		String roomStatusId = req.getParameter("roomStatusId");
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		Reservation g = gLogic.EditRoomStatusS(resvId, roomStatusId);
		resp.setContentType("text/plain; charset=UTF-8");
		if (g != null) {
			resp.getWriter().println(gson.toJson(true));
		} else {
			resp.getWriter().println(gson.toJson(false));
		}
	}

	private void EditPackageS(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		Gson gson = new Gson();
		long resvId = Long.parseLong(req.getParameter("resvId"));
		String packageId = req.getParameter("packageId");
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		Reservation g = gLogic.EditPackageS(resvId, packageId);
		resp.setContentType("text/plain; charset=UTF-8");
		if (g != null) {
			resp.getWriter().println(gson.toJson(true));
		} else {
			resp.getWriter().println(gson.toJson(false));
		}
	}
	private void AddResInGroup(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		Gson gson = new Gson();
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		String roomtypeNew = req.getParameter("roomtypeNew");
		String roomNew = req.getParameter("roomNew");
		String guestIdNew = req.getParameter("guestIdNew");
		String guestNameNew = req.getParameter("guestNameNew");
		String guestLastNameNew = req.getParameter("guestLastNameNew");
		String telNew = req.getParameter("telNew");
		String guestId = "";
		if(guestIdNew.equals("0") && !guestNameNew.equals("")){
			Guest guest = new Guest();
			GuestLogic gLogic = new GuestLogic(req,resp);
			guest = gLogic.AddGuest(0, guestNameNew, guestLastNameNew, telNew, "");
			guestId = String.valueOf(guest.getId());
		}else{
			guestId = guestIdNew;
		}
		String adultNew = req.getParameter("adultNew");
		String childNew = req.getParameter("childNew");
		String roomStatusNew = req.getParameter("roomStatusNew");
		String dateNew = req.getParameter("dateNew");

		String spanNew = req.getParameter("spanNew");
		String packageNew = req.getParameter("packageNew");
		String priceNew = req.getParameter("priceNew");
		String groupIdNew = req.getParameter("groupIdNew");
		String agencyId = req.getParameter("agencyId");

		ReservationLogic gLogic = new ReservationLogic(req,resp);
		List<EffectedRoom> effectedlist = new ArrayList<EffectedRoom>();
		Date date = formatter.parse(dateNew);
		long span = Long.parseLong(spanNew);
		long roomId = Long.parseLong(roomNew);
		Reservation temp = new Reservation();
		temp.setHotelId(hotelId);
		temp.setDate(date);
		temp.setSpan(span);
		boolean canMove = gLogic.CanBeMoveToRoom(temp,roomId);
		List<Object> rsObj = new ArrayList<Object>();
		if(canMove)
		{
			long order = 0;
			List<SubReservation> list = gLogic.GetReservationWithinDateInSpecificRoom(hotelId,date,span,roomId);
			for(SubReservation s : list)
			{
				Reservation parent = s.getParent();
				Date chkDateTo = temp.getDateTo();
				if(!s.getDateTo().after(chkDateTo) &&
					parent.getSellRoom())
					{
						if(order < parent.getOrder()) order = parent.getOrder();
					}
				else{
					Room r = gLogic.AutoMoveRoom(s,roomId);
					long id = (s.getId() > 0)? s.getId():s.getParentId();
					effectedlist.add(new EffectedRoom(id,r.getId()));
				}
			}
			Reservation g = gLogic.AddResInGroup(roomtypeNew, roomNew,
					guestId, adultNew,childNew, roomStatusNew, dateNew, spanNew, packageNew,
					priceNew, groupIdNew,hotelId,agencyId);
			Group group = gLogic.GetGroup(Long.parseLong(groupIdNew));
			group.getListResvString();
			String resListString ="";
			if(group.getListResvString() == null)
				resListString=String.valueOf(g.getId());
			else
				resListString=group.getListResvString() + "," + g.getId();
			gLogic.EditResList(Long.parseLong(groupIdNew),resListString);
			
			effectedlist.add(new EffectedRoom(g.getId(),Long.parseLong(roomNew)));
			g.getPackageByDate();
			g.getChargeList();
			rsObj = Arrays.asList(effectedlist,g);
		}

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rsObj));
	}

	private void EditAdultS(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long resvId = Long.parseLong(req.getParameter("resvId"));
		String adult = req.getParameter("adult");
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		long adultvalue = Long.parseLong(adult);
		Reservation r = gLogic.EditAdultS(resvId, adultvalue);

		List<SubReservation> subList = r.getSubReservationList();
		if(subList == null || subList.size() == 0)
		{
			SubReservation sub = new SubReservation();
			sub.CloneReservation(r);
			subList.add(sub);
		}
		new ChargeLogic(req,resp).CalCharge(r.getHotelId(), subList, r.getPackageByDate(),r.getDate(),r.getDateTo());

		resp.setContentType("text/plain; charset=UTF-8");
		boolean a =false;
		if (r != null) {
			 a = true;
		}
		resp.getWriter().println(gson.toJson(a));
	}

	private void EditChildS(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long resvId = Long.parseLong(req.getParameter("resvId"));
		String child = req.getParameter("child");
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		Reservation r = gLogic.EditChildS(resvId, Long.parseLong(child));
		
		List<SubReservation> subList = r.getSubReservationList();
		if(subList == null || subList.size() == 0)
		{
			SubReservation sub = new SubReservation();
			sub.CloneReservation(r);
			subList.add(sub);
		}
		new ChargeLogic(req,resp).CalCharge(r.getHotelId(), subList, r.getPackageByDate(),r.getDate(),r.getDateTo());

		resp.setContentType("text/plain; charset=UTF-8");
		boolean a = false;
		if (r != null) {
			a = true;
		} 
		resp.getWriter().println(gson.toJson(a));
	}

	private void EditSpanS(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		Gson gson = new Gson();
		long resvId = Long.parseLong(req.getParameter("resvId"));
		long span = Long.parseLong(req.getParameter("span"));
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		Reservation res = gLogic.GetReservation(resvId);
		if(res.getSubReservationList().size() == 0){
			gLogic.EditSpanS(resvId, String.valueOf(span));
		}else{
			List<SubReservation> subres = res.getSubReservationList();
			Date newDateTo = Util.addDays(res.getDate(), span);
			List<SubReservation> listfordelete = new SubReservationLogic(req,resp).GetSubReservationForDetele(resvId,newDateTo);
			if(span >= res.getSpan()){
				Date lastdate = subres.get(0).getDateTo();
				int indexlastsubres = 0;
				for(int i=0;i<res.getSubReservationList().size();i++){
					if(subres.get(i).getDateTo().after(lastdate)){
						lastdate = subres.get(i).getDateTo();
						indexlastsubres = i;
					}
				}
				SubReservation lastsubres = subres.get(indexlastsubres);
				Date dateTo4Last = Util.addDays(res.getDate(), span);
				lastsubres.setDateTo(dateTo4Last); // dateTo subreservation
				int lastspan = Util.daysBetween(subres.get(indexlastsubres).getDate(), Util.addDays(res.getDate(), span));
				Long lastsubresId = lastsubres.getId(); //id subreservation
				new SubReservationLogic(req,resp).EditSubReservation(lastsubresId, dateTo4Last, lastspan);
			}else{
				if(listfordelete.size() != 0){
					for(int i=0;i<listfordelete.size();i++){
							if(listfordelete.get(i).getSpan() == 1){
								//delete subres in entity and subreservatiomlist in reservation
								new SubReservationLogic(req,resp).DeleteSubReservation(listfordelete.get(i).getId());
							}else{
								int newspan = Util.daysBetween(listfordelete.get(i).getDate(), newDateTo);
								new SubReservationLogic(req,resp).EditSubReservation(listfordelete.get(i).getId(), newDateTo, newspan);
								listfordelete.remove(i);
								i = -1;
							}
						
					}
				}
			}
			for(int i=0;i<subres.size();i++){
				for(int j=0;j<listfordelete.size();j++){
					if(subres.get(i).getId() == listfordelete.get(j).getId()){
						subres.remove(i);
						i=0;
						break;
					}
				}
			}
			String subresstring = "";
			for(int d = 0;d<subres.size();d++){
			subresstring += subres.get(d).getId()+",";
	}
			new ReservationLogic(req,resp).EditSubResString(resvId, subresstring.substring(0, subresstring.length() - 1));
			gLogic.EditSpanS(resvId, String.valueOf(span));
			
		}
		 

		resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(true));

	}

	private void EditDateS(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {

		Gson gson = new Gson();
		long resvId = Long.parseLong(req.getParameter("resvId"));
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Date date = formatter.parse(req.getParameter("dateCheckIn"));
		Date newDate = date;
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		List<SubReservation> subres = gLogic.GetReservation(resvId).getSubReservationList();
		if(subres.size() == 0){
			gLogic.EditDateS(resvId, newDate);
		}else{
			Reservation res = gLogic.GetReservation(resvId);
			SubReservationLogic subResLogic = new SubReservationLogic(req,resp);
			Date oldDateFrom = res.getDate();
			for(int i=0;i<subres.size();i++){
				if(subres.get(i).getDate().equals(oldDateFrom)){
					oldDateFrom = subres.get(i).getDateTo();
					subResLogic.EditDateAndDateTo(subres.get(i).getId(), date, Util.addDays(date, subres.get(i).getSpan()));
					date = Util.addDays(date, subres.get(i).getSpan());
					i=0;
				}
			}
			gLogic.EditDateS(resvId, newDate);
		}
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(true));

	}

	private void GetReservation(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		Gson gson = new Gson();
		long resvId;
		if(!req.getParameter("resId").equals("")){
			resvId = Long.parseLong(req.getParameter("resId"));
			ReservationLogic gLogic = new ReservationLogic(req,resp);
			ChargeLogic chargeLogic = new ChargeLogic(req,resp);
			Reservation g = gLogic.GetReservation(resvId);
			if (g != null) {
				ReservationDataFull gFull = new ReservationDataFull();
				gFull.setId(g.getId());
				gFull.setDate(g.getDate());
				gFull.setDateTo(g.getDateTo());
				gFull.setDateCheckin(g.getDateCheckin());
				gFull.setSpan(g.getSpan());
				gFull.setRoomString(g.getRoomString());
				gFull.setRoomName(g.getRoom().getRoomName());
				gFull.setRoomTypeString(g.getRoomTypeString());
				gFull.setRoomTypeName(g.getRoomType().getShortName());
				gFull.setPriceRateString(g.getPackageByDateString());
				gFull.setObjective(g.getObjective());
				List<PackageByDate> pbd = g.getPackageByDate();
				String packageName = "";
				for(int x=0;x<pbd.size();x++){
					if(packageName == "") packageName = pbd.get(x).getPackages().getName();
					else if(!packageName.equals(pbd.get(x).getPackages().getName())) packageName = "Multiple Package";
					//packageName += pbd.get(x).getPackages().getName()+",";
				}
				gFull.setPriceRateName(packageName);
				
				gFull.setAdult(g.getAdult());
				gFull.setChild(g.getChild());
				gFull.setAssign(g.isAssign());
				gFull.setGuestString(g.getGuestString());
				if(!g.getGuestString().equals("0")){
					gFull.setGuestName(g.getGuest().getFirstName());
					gFull.setGuestLastName(g.getGuest().getLastName());
					gFull.setGuestAddress(g.getGuest().getAddressLine1()+" "+g.getGuest().getAddressLine2());
					gFull.setGuestTel(g.getGuest().getPhone());
				}
				gFull.setAdditionalGuestString(g.getAdditionalGuestString());
				gFull.setReservationStatusString(g.getReservationStatusString());
				gFull.setReservationStatusName(g.getReservationStatus().getTitle());
				gFull.setOrder(g.getOrder());
				gFull.setSellRoom(g.getSellRoom());
				gFull.setNote(g.getNote());
				gFull.setGroupIdString(g.getGroupIdString());
				gFull.setGroupId(g.getGroupIdNumber());
				gFull.setTaskListString(g.getTaskListString());
				gFull.setCreditString(g.getCreditString());
				gFull.setAgencyIdString(g.getAgencyIdString());
				if(!g.getAgencyIdString().equals("0")){
					gFull.setAgencyName(g.getAgencyId().getAgency());
				}else{
					gFull.setAgencyName("-");
				}
				gFull.setSourcesString(g.getSourcesString());
				gFull.setExtrabed(g.getExtrabed());
				gFull.setPaymentListString(g.getPaymentListString());
				gFull.setChargeListString(g.getChargeListString());
				gFull.setOtherChargeListString(g.getOtherChargeString());
				gFull.setFolioListString(g.getFolioListString());
				gFull.setTravelString(g.getTravelString());
				gFull.setStatus(g.isStatus());
				gFull.setAvaliable(g.isAvaliable());
				
				gFull.setCancelCheckin(chargeLogic.CheckChargeInUse(g.getOtherChargeString(),"CancelCheckin"));
				gFull.setCancelCheckout(chargeLogic.CheckChargeInUse(g.getOtherChargeString(),"CancelCheckout"));
				gFull.setCancelRes(chargeLogic.CheckChargeInUse(g.getOtherChargeString(),"CancelRes"));
				gFull.setChargeNoshow(chargeLogic.CheckChargeInUse(g.getOtherChargeString(),"Noshow"));
				gFull.setEarlyCheckin(chargeLogic.CheckChargeInUse(g.getOtherChargeString(),"EarlyCheckin"));
				gFull.setEarlyCheckout(chargeLogic.CheckChargeInUse(g.getOtherChargeString(),"EarlyCheckout"));
				gFull.setLateCheckout(chargeLogic.CheckChargeInUse(g.getOtherChargeString(),"LateCheckout"));
				
				if(g.getSubReservationList().size() != 0){
					String subreservationroomname = "";
					for(int b = 0;b< g.getSubReservationList().size();b++){
						subreservationroomname += g.getSubReservationList().get(b).getRoom().getRoomName() + ",";
					}
					gFull.setSubreservationroomname(subreservationroomname.substring(0, subreservationroomname.length() - 1));
				}
				
				double tax = 0;
				double pay = 0;
				double otherCharge = 0;
				TaxLogic taxLogic = new TaxLogic(req,resp);
				if(g.getChargeListString()!=null&&!g.getChargeListString().equals("undefined")){
					for(int i = 0;i<g.getChargeList().size();i++){
						if(i > 0){
							otherCharge = g.getChargeList().get(i).getChargeAmount();
						}
						tax += taxLogic.CalTax(g.getHotelId(), g.getChargeList().get(i).getChargeAmount());
					}
				}
				if(g.getPaymentList() != null || !g.getPaymentListString().equals("")){
					for(int i = 0;i<g.getPaymentList().size();i++){
						pay += g.getPaymentList().get(i).getAmount();
					}
				}
				if(!g.getGroupIdString().equals("0")){
				if(g.getGroupId().getPaymentList() != null || g.getGroupId().getPaymentListString() == ""){
					for(int i = 0;i <g.getGroupId().getPaymentList().size();i++){
						pay += g.getGroupId().getPaymentList().get(i).getAmount();
					}
				}
				}
				gFull.setTax(tax);
				gFull.setOtherCharge(otherCharge);
				gFull.setPay(pay);
				resp.setContentType("text/plain; charset=UTF-8");
				resp.getWriter().println(gson.toJson(gFull));
			}
		}else{
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(null));
		}
	}
	private void GetReservationAll(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		String typeFunction = req.getParameter("func");
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		Gson gson = new Gson();
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		String dateCheckin = req.getParameter("dateCheckin");
		String dateCheckout = req.getParameter("dateCheckout");
		String typeReservation = req.getParameter("typereservation");
		String SearchAll_checkoutPage = req.getParameter("SearchAll_checkoutPage");
		long line = 0;
		long pointer = 0;
		line = Long.parseLong(req.getParameter("line"));
		pointer = Long.parseLong(req.getParameter("pagePointer"));
		List<ReservationDataForReport> g = new ArrayList<ReservationDataForReport>();
		List<ReservationDataForReport> p = new ArrayList<ReservationDataForReport>();
		if(typeFunction.equals("getReservationAllGroup")){
			p = gLogic.GetReservationAllReport(hotelId,"AllGroup",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"AllGroup",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllSingle")){
			p = gLogic.GetReservationAllReport(hotelId,"AllSingle",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"AllSingle",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAll")){
			p = gLogic.GetReservationAllReport(hotelId,"All",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"All",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllCheckoutOnlyGroup")){
			p = gLogic.GetReservationAllReportCheckoutOnly(hotelId,"CheckOutOnlyGroup",dateCheckin,dateCheckout,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportCheckoutOnlyPage(hotelId,"CheckOutOnlyGroup",dateCheckin,dateCheckout,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllCheckoutOnlySingle")){
			p = gLogic.GetReservationAllReportCheckoutOnly(hotelId,"CheckOutOnlySingle",dateCheckin,dateCheckout,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportCheckoutOnlyPage(hotelId,"CheckOutOnlySingle",dateCheckin,dateCheckout,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllCheckoutOnly")){
			p = gLogic.GetReservationAllReportCheckoutOnly(hotelId,"CheckoutOnly",dateCheckin,dateCheckout,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportCheckoutOnlyPage(hotelId,"CheckoutOnly",dateCheckin,dateCheckout,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationExpressCheckOut")){
			p = gLogic.GetReservationAllReportCheckoutOnly(hotelId,"ExpressAll",dateCheckin,dateCheckout,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportCheckoutOnlyPage(hotelId,"ExpressAll",dateCheckin,dateCheckout,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationExpressCheckOutSingle")){
			p = gLogic.GetReservationAllReportCheckoutOnly(hotelId,"ExpressSingle",dateCheckin,dateCheckout,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportCheckoutOnlyPage(hotelId,"ExpressSingle",dateCheckin,dateCheckout,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationExpressCheckOutGroup")){
			p = gLogic.GetReservationAllReportCheckoutOnly(hotelId,"ExpressGroup",dateCheckin,dateCheckout,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportCheckoutOnlyPage(hotelId,"ExpressGroup",dateCheckin,dateCheckout,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllCheckinPendingOnlyGroup")){
			p = gLogic.GetReservationAllReport(hotelId,"CheckInPendingGroup",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"CheckInPendingGroup",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllCheckinPendingOnlySingle")){
			p = gLogic.GetReservationAllReport(hotelId,"CheckInPendingSingle",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"CheckInPendingSingle",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllCheckinPendingOnly")){
			p = gLogic.GetReservationAllReport(hotelId,"CheckInPending",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"CheckInPending",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllTempGroup")){
			p = gLogic.GetReservationAllReport(hotelId,"TempGroup",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"TempGroup",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllTempSingle")){
			p = gLogic.GetReservationAllReport(hotelId,"TempSingle",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"TempSingle",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllTemp")){
			p = gLogic.GetReservationAllReport(hotelId,"Temp",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"Temp",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllCheckoutPendingGroup")){
			p = gLogic.GetReservationAllReportCheckoutOnly(hotelId,"CheckOutPendingGroup",dateCheckin,dateCheckout,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportCheckoutOnlyPage(hotelId,"CheckOutPendingGroup",dateCheckin,dateCheckout,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllCheckoutPendingSingle")){
			p = gLogic.GetReservationAllReportCheckoutOnly(hotelId,"CheckOutPendingSingle",dateCheckin,dateCheckout,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportCheckoutOnlyPage(hotelId,"CheckOutPendingSingle",dateCheckin,dateCheckout,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllCheckoutPending")){
			p = gLogic.GetReservationAllReportCheckoutOnly(hotelId,"CheckOutPending",dateCheckin,dateCheckout,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportCheckoutOnlyPage(hotelId,"CheckOutPending",dateCheckin,dateCheckout,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationBookingDepositsGroup")){
			p = gLogic.GetReservationAllReport(hotelId,"DepositsGroup",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"DepositsGroup",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationBookingDepositsSingle")){
			p = gLogic.GetReservationAllReport(hotelId,"DepositsSingle",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"DepositsSingle",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationBookingDeposits")){
			p = gLogic.GetReservationAllReport(hotelId,"Deposits",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"Deposits",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllGuestNameGroup")){
			p = gLogic.GetReservationAllReport(hotelId,"GuestNameGroup",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"GuestNameGroup",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllGuestNameSingle")){
			p = gLogic.GetReservationAllReport(hotelId,"GuestNameSingle",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"GuestNameSingle",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllGuestName")){
			p = gLogic.GetReservationAllReport(hotelId,"GuestName",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"GuestName",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllCancelResvSingle")){
			p = gLogic.GetReservationAllReport(hotelId,"CancelResvSingle",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"CancelResvSingle",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllCancelResvGroup")){
			p = gLogic.GetReservationAllReport(hotelId,"CancelResvGroup",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"CancelResvGroup",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllCancelResv")){
			p = gLogic.GetReservationAllReport(hotelId,"CancelResv",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"CancelResv",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationNoShow")){
			p = gLogic.GetReservationAllReport(hotelId,"NoShow",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"NoShow",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationNoShowSingle")){
			p = gLogic.GetReservationAllReport(hotelId,"NoShowSingle",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"NoShowSingle",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationNoShowGroup")){
			p = gLogic.GetReservationAllReport(hotelId,"NoShowGroup",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"NoShowGroup",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllPaymentTracker")){
			p = gLogic.GetReservationAllReport(hotelId,"PaymentTracker",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"PaymentTracker",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllPaymentTrackerSingle")){
			p = gLogic.GetReservationAllReport(hotelId,"PaymentTrackerSingle",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"PaymentTrackerSingle",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}else if(typeFunction.equals("getReservationAllPaymentTrackerGroup")){
			p = gLogic.GetReservationAllReport(hotelId,"PaymentTrackerGroup",dateCheckin,dateCheckout,typeReservation,SearchAll_checkoutPage);
			g = gLogic.GetReservationAllReportPage(hotelId,"PaymentTrackerGroup",dateCheckin,dateCheckout,typeReservation,line,pointer,SearchAll_checkoutPage);
		}
		resp.setContentType("text/plain; charset=UTF-8");
		if (g != null) {
				List<List<ReservationDataForReport>> rsObj = new ArrayList<List<ReservationDataForReport>>();
				rsObj.add(g);
				rsObj.add(p);
				resp.getWriter().println(gson.toJson(rsObj));
			}
	}
	private void GetReservationAllCount(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		Gson gson = new Gson();
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		String dateCheckin = req.getParameter("dateCheckin");
		String dateCheckout = req.getParameter("dateCheckout");
		List<ReservationDataForReport> g = null;
		HashMap<String,Object> data = new HashMap<String,Object>();
		g = gLogic.GetReservationAllReport(hotelId,"AllCount",dateCheckin,dateCheckout,"","");
		if(g.size()!=0){
			int count = 0;
			for(int i = 0;i<g.size();i++){
				if(g.get(i).getGroupIdString()!=null)
					count += g.get(i).getSubList().size();
				else
					count++;
			}
			data.put("AllCount",count);
		}
		g = gLogic.GetReservationAllReportCheckoutOnly(hotelId,"CheckoutOnlyCount",dateCheckin,dateCheckout,"");
		if(g.size()!=0){
			int count = 0;
			for(int i = 0;i<g.size();i++){
				if(g.get(i).getGroupIdString()!=null)
					count += g.get(i).getSubList().size();
				else
					count++;
			}
			data.put("CheckoutOnlyCount",count);
		}
		g = gLogic.GetReservationAllReportCheckoutOnly(hotelId,"ExpressAllCount",dateCheckin,dateCheckout,"");
		if(g.size()!=0){
			int count = 0;
			for(int i = 0;i<g.size();i++){
				if(g.get(i).getGroupIdString()!=null)
					count += g.get(i).getSubList().size();
				else
					count++;
			}
			data.put("ExpressAllCount",count);
		}
		g = gLogic.GetReservationAllReport(hotelId,"CheckInPendingCount",dateCheckin,dateCheckout,"","");
		if(g.size()!=0){
			int count = 0;
			for(int i = 0;i<g.size();i++){
				if(g.get(i).getGroupIdString()!=null)
					count += g.get(i).getSubList().size();
				else
					count++;
			}
			data.put("CheckInPendingCount",count);
		}
		g = gLogic.GetReservationAllReport(hotelId,"TempCount",dateCheckin,dateCheckout,"","");
		if(g.size()!=0){
			int count = 0;
			for(int i = 0;i<g.size();i++){
				if(g.get(i).getGroupIdString()!=null)
					count += g.get(i).getSubList().size();
				else
					count++;
			}
			data.put("TempCount",count);
		}
		g = gLogic.GetReservationAllReportCheckoutOnly(hotelId,"CheckOutPendingCount","","","");
		if(g.size()!=0){
			int count = 0;
			for(int i = 0;i<g.size();i++){
				if(g.get(i).getGroupIdString()!=null)
					count += g.get(i).getSubList().size();
				else
					count++;
			}
			data.put("CheckOutPendingCount",count);
		}
		g = gLogic.GetReservationAllReport(hotelId,"DepositsCount",dateCheckin,dateCheckout,"","");
		if(g.size()!=0){
			int count = 0;
			for(int i = 0;i<g.size();i++){
				if(g.get(i).getGroupIdString()!=null)
					count += g.get(i).getSubList().size();
				else
					count++;
			}
			data.put("DepositsCount",count);
		}
		g = gLogic.GetReservationAllReport(hotelId,"GuestNameCount",dateCheckin,dateCheckout,"","");
		if(g.size()!=0){
			int count = 0;
			for(int i = 0;i<g.size();i++){
				if(g.get(i).getGroupIdString()!=null)
					count += g.get(i).getSubList().size();
				else
					count++;
			}
			data.put("GuestNameCount",count);
		}
		g = gLogic.GetReservationAllReport(hotelId,"CancelResvCount",dateCheckin,dateCheckout,"","");
		if(g.size()!=0){
			int count = 0;
			for(int i = 0;i<g.size();i++){
				if(g.get(i).getGroupIdString()!=null)
					count += g.get(i).getSubList().size();
				else
					count++;
			}
			data.put("CancelResvCount",count);
		}
		g = gLogic.GetReservationAllReport(hotelId,"NoShowCount",dateCheckin,dateCheckout,"","");
		if(g.size()!=0){
			int count = 0;
			for(int i = 0;i<g.size();i++){
				if(g.get(i).getGroupIdString()!=null)
					count += g.get(i).getSubList().size();
				else
					count++;
			}
			data.put("NoShowCount",count);
		}
		g = gLogic.GetReservationAllReport(hotelId,"PaymentTrackerCount",dateCheckin,dateCheckout,"","");
		if(g.size()!=0){
			int count = 0;
			for(int i = 0;i<g.size();i++){
				if(g.get(i).getGroupIdString()!=null)
					count += g.get(i).getSubList().size();
				else
					count++;
			}
			data.put("PaymentTrackerCount",count);
		}
		resp.getWriter().println(gson.toJson(data));
	}
	private void GetReservationAllCheckin(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, ParseException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Date date = formatter.parse(req.getParameter("dateCheckIn"));
		long roomtype = Long.parseLong(req.getParameter("roomtypeId"));
		long roomId = Long.parseLong(req.getParameter("roomId"));
		Date maxDate = new Date(date.getTime());
		List<Reservation> rsv = new ReservationLogic(req,resp)
				.GetRoomUsedBetweenCheckin(hotelId, maxDate, roomtype, roomId);

		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rsv));
	}

	private void GetReservationAllCheckout(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, ParseException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Date date = formatter.parse(req.getParameter("dateCheckIn"));
		long roomtype = Long.parseLong(req.getParameter("roomtypeId"));
		long roomId = Long.parseLong(req.getParameter("roomId"));
		Date maxDate = new Date(date.getTime());
		List<Reservation> rsv = new ReservationLogic(req,resp)
				.GetRoomUsedBetweenCheckout(hotelId, maxDate, roomtype, roomId);

		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rsv));
	}

	private void EditReservationGroupCheckin(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, ParseException, EntityNotFoundException {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Date date = formatter.parse(req.getParameter("dateCheckIn"));
		long groupId = Long.parseLong(req.getParameter("groupId"));
			Date maxDate = new Date(date.getTime());
			Group rsv = new ReservationLogic(req,resp).EditDateCheckinGroup(groupId,maxDate);
			
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rsv));
	}
	
	private void GetResavetionStatusCheck(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		Gson gson = new Gson();
		long roomStatusId = Long.parseLong(req.getParameter("roomStatusId"));
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		ReservationStatus g = gLogic.GetReservationStatusCheck(roomStatusId);

		resp.setContentType("text/plain; charset=UTF-8");
		if (g != null) {
			resp.getWriter().println(gson.toJson(g));
		} else {
			resp.getWriter().println(gson.toJson(g));
		}
	}

	private void GetGroupResavetionStatusCheck(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		Gson gson = new Gson();
		long groupId = Long.parseLong(req.getParameter("groupId"));
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		Group g = null;
		if (groupId != 0) {
			g = gLogic.GetReservationGroup(groupId);
		}
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(g));
	}
	
	private void GetGroup(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		Gson gson = new Gson();
		long groupId = Long.parseLong(req.getParameter("groupId"));
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		Group g = null;
		resp.setContentType("text/plain; charset=UTF-8");
		if (groupId != 0) {
			g = gLogic.GetReservationGroup(groupId);
			resp.getWriter().println(gson.toJson(g));
		}else{
			resp.getWriter().println(gson.toJson(null));
		}
		
	}
	
	private void LoadBookingDetail(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, ParseException {
		long groupId = Long.parseLong(req.getParameter("gId"));
		long reservedId = Long.parseLong(req.getParameter("reservedId"));
		Gson gson = new Gson();
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		if(groupId != 0)
		{
			String pd = resLogic.LoadBookingDetail(groupId,true);
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(pd));
		}
		else
		{
			PaymentData pd = resLogic.LoadSingleBookingDetail(reservedId);
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(pd));
		}
		
	}
	private void EditCharge(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		HttpSession session = req.getSession(true);
		Gson gson = new Gson();
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		String dataCharge =req.getParameter("dataCharge");
		long resId = Long.parseLong(req.getParameter("resId"));
		boolean isroomCharge = new ChargeLogic(req,resp).GetCharge(Long.parseLong(dataCharge)).isRoomCharge();
		Reservation g =new  ReservationLogic(req,resp).EditReservationCharge(hotelId,resId, dataCharge, isroomCharge);

		resp.setContentType("text/plain; charset=UTF-8");
		if (g != null) {
			resp.getWriter().println(gson.toJson(true));
		} else {
			resp.getWriter().println(gson.toJson(false));
		}
	}
	private void EditChargeGroup(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		HttpSession session = req.getSession(true);
		Gson gson = new Gson();
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		String dataCharge =req.getParameter("dataCharge");
		long groupId = Long.parseLong(req.getParameter("groupId"));

		boolean isroomCharge = new ChargeLogic(req,resp).GetCharge(Long.parseLong(dataCharge)).isRoomCharge();
		Group g = new ReservationLogic(req,resp).EditChargeGroup(hotelId,groupId, dataCharge, isroomCharge);

		resp.setContentType("text/plain; charset=UTF-8");
		if (g != null) {
			resp.getWriter().println(gson.toJson(true));
		} else {
			resp.getWriter().println(gson.toJson(false));
		}
	}
	private void AddReservationStatus(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		HttpSession session = req.getSession(true);
		Gson gson = new Gson();
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		ReservationLogic reservationLogic = new ReservationLogic(req,resp);
		String titleResStatus = req.getParameter("title");
		String ColorresStatus = "#FA5858";
		ReservationStatus res = reservationLogic.addReservationStatus(hotelId,titleResStatus,ColorresStatus);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(res));

	}

	private void LoadGuestList(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, ParseException, NumberFormatException, EntityNotFoundException {
		String resId = req.getParameter("resId");
		Reservation res = new ReservationLogic(req,resp).GetReservation(Long.parseLong(resId));
		 Gson gson = new Gson();
		 if(res!=null&&res.getAdditionalGuest()!= null){
			 List <Guest> list =res.getAdditionalGuest();
			 List<GuestData> guestData = new GuestLogic(req,resp).GetGuestList(list,Long.parseLong(resId));	
			
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(guestData)); 
		 }else{
			 resp.getWriter().println(gson.toJson(null)); 
		 }
	}
	
	private void InsertGuest(HttpServletRequest req,HttpServletResponse resp) throws IOException, EntityNotFoundException, ParseException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long resId = Long.parseLong(req.getParameter("resId"));
		long salutationId =Long.parseLong(req.getParameter("salutationId"));
		String name = req.getParameter("name");
		String lastName = req.getParameter("lastName");
		String phone = req.getParameter("phone");
		String mail = req.getParameter("mail");
		GuestLogic guestLogic = new GuestLogic(req,resp);
		GuestData gd = new GuestData();
		ReservationLogic reservationlogic = new ReservationLogic(req,resp);
		Reservation res = reservationlogic.GetReservation(resId);
		long guestAmount = res.getAdult()+res.getChild();
		long maxocc = res.getRoomType().getMaxOccupancy();
		if(guestAmount<maxocc){
		Guest gs = guestLogic.AddGuest(salutationId, name, lastName,phone , mail);
		if(res.getGuestString().equals("0")){
			res.setGuestString(String.valueOf(gs.getId()));
			reservationlogic.UpdateReservation(res);
		}
		String guestId = String.valueOf(gs.getId());
		reservationlogic.EditAdditionalGuest(hotelId, resId, guestId);
		gd.setId(gs.getId());
		gd.setName(gs.getFirstName() + " "+ gs.getLastName());
		if(gs.getSalutation()!= null)
		{
			gd.setSName(gs.getSalutation().getTitle());
		}
		gd.setPhone(gs.getPhone());
		gd.setMail(gs.getMail());
		gd.setIdNumber(gs.getIdNumber());
		}
		else
		{
			gd = null;
		}
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(gd));
	}
	
	private void RemoveGuestFormRes(HttpServletRequest req,HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		
		long reservedId = Long.parseLong(req.getParameter("resId"));
		String guestIdString = req.getParameter("guestIdString");
		ReservationLogic res = new ReservationLogic(req,resp);
		Reservation  rsv =res.DeleteAdditionalGuest(hotelId,reservedId,guestIdString);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rsv));

	}
	
	private void AddResFromEmpty1(long hotelId, HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException {
		Gson gson = new Gson();
		try {					
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
					Locale.ENGLISH);
			Date date = formatter.parse(req.getParameter("date"));
			long span = Long.parseLong(req.getParameter("span"));
			String roomId = req.getParameter("room");
			String roomType = req.getParameter("roomType");
			long roomAmount = 1;
			String priceRateId = req.getParameter("priceRate");
			long adult = Long.parseLong(req.getParameter("adult"));
			long child = Long.parseLong(req.getParameter("child"));
			boolean isAssign = Boolean.parseBoolean(req.getParameter("isAssign"));
			GenericLogic generalLogic = new GenericLogic(req,resp);
			ReservationStatus rsv = generalLogic.GetReservationStatus(hotelId,"Reserved Rooms");
			String reservationStatus = Long.toString(rsv.getId());
			// wait for auto suggest
			String GuestId = "0";

			long salutatinId = 0;
			String name = req.getParameter("name");
			String lastName = req.getParameter("lastname");
			String phone = req.getParameter("tell");
			String mail = "";
			Double pay = Double.parseDouble(req.getParameter("pay"));
			String address = req.getParameter("address");
			String sources = req.getParameter("sourcesId");
			String reason = req.getParameter("reason");
			long extrabed = Long.parseLong(req.getParameter("extrabed"));
			String guestnamelist = req.getParameter("arrayguestname");
			String guestsolutationlist = req.getParameter("arrayguestsolutation");
			String guestlastnamelist = req.getParameter("arrayguestlastname");
			String guestphonelist = req.getParameter("arrayguestphone");
			String guestemaillist = req.getParameter("arrayguestemail");
			String agencyId =  req.getParameter("agency");
			String company = req.getParameter("company");
			String note = req.getParameter("note");
			String arrive = req.getParameter("arrive");
			String arriveBack = req.getParameter("arriveBack");
			String time =  req.getParameter("time");
			String timeBack = req.getParameter("timeBack");
			String goBy = req.getParameter("goBy");
			String goByBack = req.getParameter("goByBack");
			if (!req.getParameter("agency").equals("") || !req.getParameter("company").equals("")) {
				AgencyLogic aLogic = new AgencyLogic(req,resp);
				long displayID = aLogic.GetMaxAgentDisplayId(hotelId);
				Agency agent = aLogic.AddAgency(hotelId,
						agencyId,company,(displayID+1));
				agencyId = String.valueOf(agent.getId());
			} else {
				agencyId = "0";
			}
			GuestLogic guestLogic = new GuestLogic(req,resp);
			ReservationLogic reservationLogic = new ReservationLogic(req,resp);

			if (GuestId.equals("0")) {
//				   arrive arriveBack time timeBack
				Guest gs = guestLogic.AddGuest(salutatinId, name, lastName,
						phone, mail);
				guestLogic.EditAddress(hotelId, gs.getId(), address);
				Reservation rse = new ReservationLogic(req,resp).CreateReservation(
						hotelId, date, span, roomId, roomType, priceRateId,
						adult, child, isAssign, String.valueOf(gs.getId()),
						reservationStatus, roomAmount, sources,
						extrabed, reason, agencyId, pay,
						guestnamelist,guestsolutationlist,guestlastnamelist,guestphonelist,guestemaillist);
				reservationLogic.SaveNoteS(hotelId, rse.getId(), note);
				if(!req.getParameter("cardNo").equals("")){
					CreditCard c = new CreditCardLogic(req,resp).AddCreditCard(hotelId, req.getParameter("cvc"),
							req.getParameter("cardType"), "", req.getParameter("cardNo"), req.getParameter("dateExpire"));
					reservationLogic.EditCreditCard2Res(rse.getId(), String.valueOf(c.getId()));
				}
				travel t = new travel();
				TravelLogic tLogic = new TravelLogic();
				SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm",Locale.ENGLISH);
				t = tLogic.Addtravel(hotelId, goBy, arrive, formatter2.parse(time), false, goByBack, arriveBack, formatter2.parse(timeBack), false,false,false);
				reservationLogic.EditTravelGroup(hotelId, 0, String.valueOf(t.getId()), String.valueOf(rse.getId()));
				resp.setContentType("text/plain; charset=UTF-8");
				resp.getWriter().println(gson.toJson(new ResultData(true)));

			} else {
				Reservation res = reservationLogic.CreateReservation(hotelId,
						date, span, roomId, roomType, priceRateId, adult,
						child, isAssign, GuestId, reservationStatus,
						roomAmount, sources, extrabed, reason, agencyId,
						pay,guestnamelist,guestsolutationlist,guestlastnamelist,guestphonelist,guestemaillist);
				reservationLogic.SaveNoteS(hotelId, res.getId(), note);
				resp.setContentType("text/plain; charset=UTF-8");
				resp.getWriter().println(gson.toJson(new ResultData(true)));
			}
		} catch (Exception e) {
			resp.getWriter().println(gson.toJson(new ResultData(false)));
		}
	}

	private void AssignRoom(HttpServletRequest req,HttpServletResponse resp) throws ParseException, IOException,
	EntityNotFoundException {
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long resId = Long.parseLong(req.getParameter("resId"));
		Boolean assign = Boolean.parseBoolean(req.getParameter("isAssign"));
		String roomId = req.getParameter("roomId");
		ReservationLogic res = new ReservationLogic(req,resp);
		Reservation rsv =res.AssignRoom(resId, assign,roomId);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rsv));
	}
	
	private void ClearGuest(HttpServletRequest req,HttpServletResponse resp) throws ParseException, IOException,
	EntityNotFoundException {	
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		
		Long resId = Long.parseLong(req.getParameter("resId"));
		
		ReservationLogic res = new ReservationLogic(req,resp); 
		Reservation old = res.GetReservation(resId);
		List<Guest> additionalguestlist = old.getAdditionalGuest();
		String additionalString = "";
		for(int i=0;i<additionalguestlist.size();i++){
			if(additionalguestlist.get(i).getId() == old.getGuest().getId()){
				additionalguestlist.remove(i);
				i--;
			}else{
				additionalString += additionalguestlist.get(i).getId()+",";
			}
		}
		
		res.DeleteAdditionalGuest(hotelId,resId, additionalString.substring(0, additionalString.length() - 1));
		Reservation rsv =res.EditGuest(resId, "0");
		Gson gson = new Gson();
		
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rsv));

	}
	
	private void CreateGuestSingleInGroup(HttpServletRequest req,HttpServletResponse resp) throws ParseException, IOException,
	EntityNotFoundException {
		Gson gson = new Gson();	
		long hotelId = 1;
		try{
			HttpSession session = req.getSession(true);
			if (session.getAttribute("hotelId") != null)
				 hotelId = (Long) session.getAttribute("hotelId");
		long resId = Long.parseLong(req.getParameter("resId"));
		String name = req.getParameter("name");
		String lastname = req.getParameter("lastname");
		String address = req.getParameter("address");
		String phone = req.getParameter("phone");
		String company = req.getParameter("company");
		String agency = req.getParameter("agency");
		Guest guest = new Guest();
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		guest = new GuestLogic(req,resp).AddFullGuest(0, name, lastname, phone, "", address, company);
		resLogic.EditGuest(resId, String.valueOf(guest.getId()));
		resLogic.EditAdditionalGuest(hotelId,resId, String.valueOf(guest.getId()));
		if(!agency.equals("-")){
			Agency a = new Agency();
			long displayID = new AgencyLogic(req,resp).GetMaxAgentDisplayId(hotelId);
			a = new AgencyLogic(req,resp).AddAgency(hotelId, agency, "",(displayID+1));
			resLogic.EditAgency(resId,a.getId());
		}
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(new ResultData(true)));
	} catch (Exception e) {
		resp.getWriter().println(gson.toJson(new ResultData(false)));
	}
	}
	
	private void GetGuestForFrontPage(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, ParseException, NumberFormatException, EntityNotFoundException {
		long resId =Long.parseLong(req.getParameter("guestId"));
		Guest guestData = new GuestLogic(req,resp).GetGuest(resId);	
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(guestData));
		
	}
	private void GetReservationInGroup(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {

		Gson gson = new Gson();
		long resvId = Long.parseLong(req.getParameter("resId"));
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		Reservation g = gLogic.GetReservation(resvId);
		resp.setContentType("text/plain; charset=UTF-8");
		if (g != null) {
			resp.getWriter().println(gson.toJson(g));
		}
	}
	
	private void CheckInResvList(HttpServletRequest req,
			HttpServletResponse resp) throws ParseException, IOException,
			EntityNotFoundException, JSONException {
		long hotelId = 1;
		HttpSession session = req.getSession(true);
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		
		String[] listResId = req.getParameter("listResId").split(",");
		List<Object> rs = new ArrayList<Object>();
		
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		GenericLogic genericLogic = new GenericLogic(req,resp);
		for(int i=0;i<listResId.length;i++)
		{
			final long resId = Long.parseLong(listResId[i]);
			Reservation res = resLogic.GetReservation(resId);
			if(res != null){
				final ReservationStatus status = genericLogic.GetReservationStatus(hotelId, StatusTitle.ReservationStatus.CheckedInRooms);
				if(res.getReservationStatus().getId() != status.getId())
				{
					res.setReservationStatus(status);
					
					JSONObject jsonObj = new JSONObject(){{
						put("resId", resId);
						put("Status",new JSONObject(status));
					}};
					
					rs.add(jsonObj);
					resLogic.UpdateReservation(res);
				}
			}
		}

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(rs);
	}
	
	private void EditResvListCheckInCheckOut(HttpServletRequest req, HttpServletResponse resp) throws ParseException, EntityNotFoundException, IOException{
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		long resId = Long.parseLong(req.getParameter("resId"));
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Date date = formatter.parse(req.getParameter("date"));
		long span = Long.parseLong(req.getParameter("span"));
		HashMap<String, Object> obj = new ReservationLogic(req,resp).EditDetailResvCheckInCheckOut(hotelId,resId,date,span);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}

	private void CreateGroupandAddRes(HttpServletRequest req, HttpServletResponse resp)
			throws ParseException, IOException, EntityNotFoundException {
		Gson gson = new Gson();
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String roomtypeNew = req.getParameter("roomtypeNew");
		String roomNew = req.getParameter("roomNew");
		String guestIdNew = req.getParameter("guestIdNew");
		String guestNameNew = req.getParameter("guestNameNew");
		String guestLastNameNew = req.getParameter("guestLastNameNew");
		String telNew = req.getParameter("telNew");
		@SuppressWarnings("unused")
		String guestId = "";
		if(guestIdNew.equals("0") && !guestNameNew.equals("")){
			Guest guest = new Guest();
			GuestLogic gLogic = new GuestLogic(req,resp);
			guest = gLogic.AddGuest(0, guestNameNew, guestLastNameNew, telNew, "");
			guestId = String.valueOf(guest.getId());
		}else{
			guestId = guestIdNew;
		}
		String adultNew = req.getParameter("adultNew");
		String childNew = req.getParameter("childNew");
		String roomStatusNew = req.getParameter("roomStatusNew");
		String dateNew = req.getParameter("dateNew");

		String spanNew = req.getParameter("spanNew");
		String packageNew = req.getParameter("packageNew");
		String priceNew = req.getParameter("priceNew");
		String groupIdNew = req.getParameter("groupIdNew");
		String agencyId = req.getParameter("agencyId");
		
		String[] roomList =roomNew.trim().split(",");
		String[] roomTypeList=roomtypeNew.trim().split(",");
		HashMap<String,Object> hash;
		List<Object> rsObj = new ArrayList<Object>();
		List<SubReservation> list = new ArrayList<SubReservation>();
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		RoomLogic roomLogic = new RoomLogic(req,resp);
		Date date = formatter.parse(dateNew);
		long span = Long.parseLong(spanNew);
		List<Room> r = new ArrayList<Room>();
		for(int i =0;i<roomList.length;i++){
			r = roomLogic.GetRoomWithCache(hotelId,Long.parseLong(roomTypeList[0]));
			list = gLogic.GetUsedRoomWithinDate(hotelId,date,span,Long.parseLong(roomTypeList[i]));
			for(SubReservation s : list)
			{
				if(s.getRoom().getId() == Long.parseLong(roomList[i]))
				{
					resp.setContentType("text/plain; charset=UTF-8");
					resp.getWriter().println(gson.toJson(null));
					return;
				}
				for (int n=0; n<r.size(); n++) {
					r.get(n);
					if (r.get(n).getId()==s.getRoom().getId())
						r.remove(n);
				} 
			}
			if(r.size() >= roomList.length)
			{
				for(int n=0; n<roomList.length; n++)
					roomList[n]=String.valueOf(r.get(n).getId());
			}else
			{
				resp.setContentType("text/plain; charset=UTF-8");
				resp.getWriter().println(gson.toJson(null));
				return;
			}
		}
		for(int n =0;n<roomList.length;n++){	
			if(groupIdNew.equals("0"))
			{
				Group gg = new ReservationLogic(req,resp).CreateGroup(req,resp,hotelId, formatter.parse(dateNew),  Long.parseLong(spanNew), 
						roomTypeList[0], packageNew, 0.0, Long.parseLong(guestIdNew), "0", "0", 
						"", 0, "0", "0");
				
				groupIdNew = String.valueOf(gg.getId());
			}
		
			Reservation g =gLogic.AddResInGroup(roomTypeList[n], roomList[n],
					"0", adultNew,childNew, roomStatusNew, dateNew, spanNew, packageNew,
					priceNew, groupIdNew,hotelId,agencyId);
			Group group = gLogic.GetGroup(Long.parseLong(groupIdNew));
			group.getListResvString();
			String resListString ="";
			if(group.getListResvString() == null)
				resListString=String.valueOf(g.getId());
			else
				resListString=group.getListResvString() + "," + g.getId();
			gLogic.EditResList(Long.parseLong(groupIdNew),resListString);
						
			hash = new HashMap<String,Object>();
			hash.put("ChargeList", g.getChargeList());
			hash.put("ResData", gLogic.FillReservationDataFullWithTask(g));
			hash.put("resId",g.getId());			
			rsObj.add(hash);
		}

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rsObj));
	}

	private void ExprotFile(HttpServletRequest req,HttpServletResponse resp) throws ParseException, IOException,
	EntityNotFoundException, ClassNotFoundException, DocumentException {
		long hotelId = 1;
		HttpSession session = req.getSession(true);
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		ReservationLogic gLogic = new ReservationLogic(req,resp);
		List<ReservationDataForReport> g = null;
		String title = req.getParameter("title");
		String code = req.getParameter("code");
		String[] type = req.getParameter("typeReservation").split(",");
		String[] status = req.getParameter("status").split(",");
		String dateCheckin = req.getParameter("dateCheckin");
		String dateCheckout = req.getParameter("dateCheckout");
		String typeExport = req.getParameter("typeExport");
		String dateCheckinShow = "";
		String dateCheckoutShow ="";
		if(dateCheckin==null&&dateCheckout==null){
			 g = gLogic.GetReservationAllReport(hotelId,"GuestName",dateCheckin,dateCheckout,status[1],"");
		}else{
			 g = gLogic.GetReservationAllReport(hotelId,"GuestName",dateCheckin,dateCheckout,status[1],"");
		}
		if(dateCheckin.equals("")){
			dateCheckinShow = "-";
			dateCheckoutShow = "-";
		}else{
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
					Locale.ENGLISH);
			Date dCheckin = formatter.parse(req.getParameter("dateCheckin"));
			Date dCheckout = formatter.parse(req.getParameter("dateCheckout"));
			Calendar cal = Calendar.getInstance();
		    cal.setTime(dCheckin);
		    int year = cal.get(Calendar.YEAR);
		    int month = cal.get(Calendar.MONTH)+1;
		    int day = cal.get(Calendar.DAY_OF_MONTH);
		    
		    Calendar calCheckout = Calendar.getInstance();
		    calCheckout.setTime(dCheckout);
		    int yearCheckout = calCheckout.get(Calendar.YEAR);
		    int monthCheckout = calCheckout.get(Calendar.MONTH)+1;
		    int dayCheckout = calCheckout.get(Calendar.DAY_OF_MONTH);
		    //General Date
			String formatdateG = new GenericLogic(req,resp).GetGeneral(hotelId).getDateFormat().getDateTimeFormat();
			SimpleDateFormat formatterG = new SimpleDateFormat(formatdateG);
			Date dateCheckinFormat = formatterG.parse(day+" "+month+" "+year);
			dateCheckinShow = formatDate(dateCheckinFormat);
			Date dateCheckoutFormat = formatterG.parse(dayCheckout+" "+monthCheckout+" "+yearCheckout);
			dateCheckoutShow = formatDate(dateCheckoutFormat);
		}
		if(code.equals("")){
			code = "-";
		}
		String typeFile = "";
		if(typeExport.equals("Excel")){//type file
			typeFile =title+".xls";
		}else if(typeExport.endsWith("Csv")){
			typeFile = title+".csv";
		}else{
			typeFile = title+".pdf";
		}
		// write it as an excel attachment
		resp.setContentType("application/x-msdownload");
		resp.setContentType("Content-Description: File Transfer");
		resp.setContentType("application/force-download; charset=UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(typeFile, "UTF-8") + "\"");
		String trText = "";
		String TextCsv = "";
		String Code = (String)session.getAttribute("LanguageCode");
		String SubCode = (String)session.getAttribute("LanguageSubcode");
	   	Locale locale = new Locale(Code, SubCode);
		ResourceBundle resource = ResourceBundle.getBundle("resource", locale);
		String StatusResInGroup = "";
		String groupId = "";
		String resId = "";
		String nameSubres = "";
		ArrayList<String> arrayListpdf = new ArrayList<String>();
		int runNo = 0;
		int indexArray = 0;
		int checkStyleTr = 0;
		String styleTr ="";
		for(int i =0;i<g.size();i++){
			runNo++;
			if(type[1].equals("G")){
				if(g.get(i).getGroupIdString()==null){
					continue;
				}
			}else if(type[1].equals("S")){
				if(g.get(i).getGroupIdString()!=null){
					continue;
				}
				if(status[1].equals("Checked-in Rooms")){
					if(!g.get(i).getReservationTitle().equals("Checked-in Rooms")){
						continue;
					}
				}else if(status[1].equals("Checked-out Rooms")){
					if(!g.get(i).getReservationTitle().equals("Checked-out Rooms")){
						continue;
					}
				}
			}
			if(checkStyleTr==0){
				styleTr = "dataRecord";
				checkStyleTr = 1;
			}else{
				styleTr = "dataRecordBot";
				checkStyleTr = 0;
			}
			if(g.get(i).getGroupIdString()!=null){
				int CheckStatusCheckin = 0;
				int CheckStatusCheckout = 0;
				for(int j =0;j<g.get(i).getSubList().size();j++){
					if(status[1].equals("Checked-in Rooms")){
						if(g.get(i).getSubList().get(j).getReservationTitle().equals("Checked-in Rooms")){
							CheckStatusCheckin++;
						}
					}else if(status[1].equals("Checked-out Rooms")){
						if(g.get(i).getSubList().get(j).getReservationTitle().equals("Checked-out Rooms")){
							CheckStatusCheckout++;
						}
					}
				}
				if(status[1].equals("Checked-in Rooms")){
					if(CheckStatusCheckin==0){
						continue;
					}
				}else if(status[1].equals("Checked-out Rooms")){
					if(CheckStatusCheckout==0){
						continue;
					}
				}
				resId = String.valueOf(g.get(i).getId());
				groupId = g.get(i).getGroupIdString();
				for(int j =0;j<g.get(i).getSubList().size();j++){
					String subResId = String.valueOf(g.get(i).getSubList().get(j).getId());
					if(checkStyleTr==0){
						styleTr = "dataRecord";
						checkStyleTr = 1;
					}else{
						styleTr = "dataRecordBot";
						checkStyleTr = 0;
					}
					if(g.get(i).getSubList().get(j).getName()!=null){
						nameSubres = g.get(i).getSubList().get(j).getName();
						String nameGuest = nameSubres.split(" ")[0];
						if(!code.equals("-")){
							if(!(code.equals(nameGuest)||code.equals(String.valueOf(g.get(i).getGroupIdString()))||code.equals(subResId))){
								continue;
							}
						}
					}else{
						if(!code.equals("-")){
							if(!(code.equals(String.valueOf(g.get(i).getGroupIdString()))||code.equals(subResId))){
								continue;
							}
						}
						nameSubres = "";
					}
					if(g.get(i).getSubList().get(j).getReservationTitle().equals("Reserved Rooms")){
						StatusResInGroup = resource.getString("RoomManagementList.CheckOut.table.statusReservedRooms");
					}else if(g.get(i).getSubList().get(j).getReservationTitle().equals("Checked-out Rooms")){
						StatusResInGroup = resource.getString("RoomManagementList.CheckOut.table.statusCheckOut");
					}else if(g.get(i).getSubList().get(j).getReservationTitle().equals("Temp Rooms")){
						StatusResInGroup = resource.getString("RoomManagementList.CheckOut.table.statusTempRooms");
					}else if(g.get(i).getSubList().get(j).getReservationTitle().equals("Cancel Reservation")){
						StatusResInGroup = resource.getString("RoomManagementList.CheckOut.table.statusCancelCheckin");
					}else{
						StatusResInGroup = resource.getString("RoomManagementList.CheckOut.table.statusCheckIn");
					}
					String dateCheckinDisplay = formatDate(g.get(i).getSubList().get(j).getDate());
					String dateCheckoutDisplay = formatDate(g.get(i).getSubList().get(j).getDateTo());
					String groupIdString = "G"+g.get(i).getGroupIdString();
					trText += "<tr class = \"centerText\">"+
						    "<td class=\""+styleTr+"\">"+runNo+"11111</td>"+
						    "<td class=\""+styleTr+"\"><span>"+groupIdString+"</span></td>"+
						    "<td class=\""+styleTr+"\"><span>'"+String.valueOf(subResId)+"'</span></td>"+
						    "<td class=\""+styleTr+"\"><span >"+nameSubres+"</span></td>"+
						    "<td class=\""+styleTr+"\"><span>"+dateCheckinDisplay+"&nbsp;&nbsp;&nbsp;</span></td>"+
						    "<td class=\""+styleTr+"\"><span>"+dateCheckoutDisplay+"&nbsp;&nbsp;&nbsp;</span></td>"+
						    "<td class=\""+styleTr+"\"><span>"+StatusResInGroup+"</span></td>"+
						    "<td class=\""+styleTr+"\"><span>"+dateCheckinDisplay+"-"+dateCheckoutDisplay+"/"+g.get(i).getSubList().get(j).getSpan()+"</span></td>"+
						    "<td class=\""+styleTr+"\"> <span>"+g.get(i).getSubList().get(j).getRoomTypeName()+"("+g.get(i).getSubList().get(j).getRoomName()+")</span></td>"+
					    "</tr>";
					String Duration = dateCheckinDisplay+"-"+dateCheckoutDisplay+"/"+g.get(i).getSubList().get(j).getSpan();
					TextCsv += runNo+","+groupIdString+","+g.get(i).getSubList().get(j).getId()+","+nameSubres+","+dateCheckinDisplay+","+dateCheckoutDisplay+","+StatusResInGroup+","+Duration+","+g.get(i).getSubList().get(j).getRoomTypeName()+"("+g.get(i).getSubList().get(j).getRoomName()+")"+System.getProperty("line.separator"); 
					arrayListpdf.add(indexArray,runNo+"#"+groupIdString+"#"+g.get(i).getSubList().get(j).getId()+"#"+nameSubres+"#"+dateCheckinDisplay+"#"+dateCheckoutDisplay+"#"+StatusResInGroup+"#"+Duration+"#"+g.get(i).getSubList().get(j).getRoomTypeName()+"("+g.get(i).getSubList().get(j).getRoomName()+")");
					indexArray++;
				}
			}else{
				String nameGuest = g.get(i).getName().split(" ")[0];
				if(!code.equals("-")){
					if(!(code.equals(nameGuest)||code.equals(String.valueOf(g.get(i).getGroupIdString()))||code.equals(String.valueOf(g.get(i).getId())))){
						continue;
					}
				}
				groupId="";
				resId = String.valueOf(g.get(i).getId());
				if(g.get(i).getReservationTitle().equals("Reserved Rooms")){
					StatusResInGroup = resource.getString("RoomManagementList.CheckOut.table.statusReservedRooms");
				}else if(g.get(i).getReservationTitle().equals("Checked-out Rooms")){
					StatusResInGroup = resource.getString("RoomManagementList.CheckOut.table.statusCheckOut");
				}else if(g.get(i).getReservationTitle().equals("Temp Rooms")){
					StatusResInGroup = resource.getString("RoomManagementList.CheckOut.table.statusTempRooms");
				}else if(g.get(i).getReservationTitle().equals("Cancel Reservation")){
					StatusResInGroup = resource.getString("RoomManagementList.CheckOut.table.statusCancelCheckin");
				}else{
					StatusResInGroup = resource.getString("RoomManagementList.CheckOut.table.statusCheckIn");
				}
				String dateCheckinDisplay = formatDate(g.get(i).getDate());
				String dateCheckoutDisplay = formatDate(g.get(i).getDateTo());
				trText += "<tr class = \"centerText\">" +
				    "<td class=\""+styleTr+"\">"+runNo+"</td>"+
				    "<td class=\""+styleTr+"\"><span>"+groupId+"</span></td>"+
				    "<td class=\""+styleTr+"\"><span>'"+String.valueOf(resId)+"'</span></td>"+
				    "<td class=\""+styleTr+"\"><span >"+g.get(i).getName()+"</span></td>"+
				    "<td class=\""+styleTr+"\"><span>"+dateCheckinDisplay+"</span></td>"+
				    "<td class=\""+styleTr+"\"><span>"+dateCheckoutDisplay+"</span></td>"+
				    "<td class=\""+styleTr+"\"><span>"+StatusResInGroup+"</span></td>"+
				    "<td class=\""+styleTr+"\"><span>"+dateCheckinDisplay+"-"+dateCheckoutDisplay+"/"+g.get(i).getSpan()+"</span></td>"+
				    "<td class=\""+styleTr+"\"> <span>"+g.get(i).getRoomTypeName()+"("+g.get(i).getRoomName()+")</span></td>"+
			    "</tr>";
				String Duration = dateCheckinDisplay+"-"+dateCheckoutDisplay+"/"+g.get(i).getSpan();
				TextCsv += runNo+","+","+resId+","+g.get(i).getName()+","+dateCheckinDisplay+","+dateCheckoutDisplay+","+StatusResInGroup+","+Duration+","+g.get(i).getRoomTypeName()+"("+g.get(i).getRoomName()+")"+System.getProperty("line.separator");				
				arrayListpdf.add(indexArray,runNo+"#"+"#"+resId+"#"+g.get(i).getName()+"#"+dateCheckinDisplay+"#"+dateCheckoutDisplay+"#"+StatusResInGroup+"#"+Duration+"#"+g.get(i).getRoomTypeName()+"("+g.get(i).getRoomName()+")");
				indexArray++;
			}
		}
		String headText = "";
		String groupCode = resource.getString("RoomManagementList.CheckOut.table.groupCode");
		String ReservationId = resource.getString("RoomManagementList.CheckOut.table.ResId");
		String groupGuestName = resource.getString("RoomManagementList.CheckOut.table.groupGuestName");
		String checkInString = resource.getString("RoomManagementList.GuestList.table.checkin");
		String checkOutString = resource.getString("RoomManagementList.GuestList.table.checkout");
		String statusString = resource.getString("RoomManagementList.CheckOut.table.Status");
		String stayDuration = resource.getString("RoomManagementList.CheckOut.table.StayDuration");
		String typeRoom = resource.getString("RoomManagementList.CheckOut.table.typeRoom");
		headText = "<tr class = \"centerText\">"+
			"<td class=\"trdataRecord\"> # </td>"+
			"<td class=\"trdataRecord\"><span>"+groupCode+"</span></td>"+
			"<td class=\"trdataRecord\"><span>"+ReservationId+"</span></td>"+
			"<td class=\"trdataRecord\"><span>"+groupGuestName+"</span></td>"+
			"<td class=\"trdataRecord\"><span>"+checkInString+"</span></td>"+
			"<td class=\"trdataRecord\"><span>"+checkOutString+"</span></td>"+
			"<td class=\"trdataRecord\"><span>"+statusString+"</span></td>"+
			"<td class=\"trdataRecord\"><span>"+stayDuration+"</span></td>"+
			"<td class=\"trdataRecord\"><span>"+typeRoom+"</span></td>"+
		"</tr>";
		String SearchNameCode = resource.getString("RoomManagementList.CheckOut.title.searchNameCode");
		String betweenDate = resource.getString("RoomManagementList.GuestList.table.betweenDate");
		String toDate = resource.getString("RoomManagementList.GuestList.table.to");
		String typeCheckin = resource.getString("RoomManagementList.CheckOut.title.typeCheckin");
		String typeresv = resource.getString("RoomManagementList.CheckedIn.table.typeresv");
		String printText = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"+
				"<html xmlns='http://www.w3.org/1999/xhtml'>"+
				"<head>"+
				"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"+
				"<title>Untitled Document</title>" +
				"<style type=\"text/css\">"+".HeadTableFil{"+"color:#FFFFFF;"+"font-size: 12px;"+"font-weight: bolder;" +"background-color: #385f9f;"+"}" +
					".center{" +"text-align:center;" +"font-size: 15px;"+"color:#FFFFFF;"+"font-weight:bold;"+"background-color: #385f9f;"+"}" +
					".centerText{" +"text-align:center;"+"}" +
					".dataRecordBot{color:black;background-color:#FFF;vertical-align:top;}"+
					".dataRecord{color:black;background-color:#E6EBF0;border-right: solid #E6EBF0 1px;vertical-align:top;}"+
					".trdataRecord{"+"background-color:#385f9f;"+"font-size: 12px;"+"color:#FFF;"+"font-weight: bolder;"+"border-right: solid #385f9f 1px;"+"}"+
				"</style>"+
				"</head>"+
				"<body>"+
					"<table width=\"900\" >"+
					"<tr>" +
					"<td colspan=\"9\" class=\"center\">" +
					title +
					"</td>"+
					"</tr>"+
						"<tr>"+
							"<td class=\"HeadTableFil\" colspan=\"9\">"+
								"<center><span>"+SearchNameCode+"</span>&nbsp;"+code+"&nbsp|&nbsp"+
								"<span>"+betweenDate+"</span>&nbsp;"+dateCheckinShow+"&nbsp|&nbsp"+
								"<span>"+toDate+"</span>&nbsp;"+dateCheckoutShow+"&nbsp|&nbsp"+
								"<span>"+typeCheckin+"</span>&nbsp;"+type[0]+"&nbsp|&nbsp"+
								"<span>"+typeresv+"</span>&nbsp;"+status[0]+
								"</center></td>"+
						"</tr>"+
					"</table>"+
					"<table width=\"900\">" +
					headText+
					trText+
					"</table>"+
				"</body>"+
				"</html>";
		String printTextFile = "";
		if(typeExport.equals("Excel")){
			resp.setContentType("Content-type: application/ms-excel");
			printTextFile = printText;
			resp.getWriter().println(printTextFile);
		}else if(typeExport.equals("Csv")){
			resp.setContentType("Content-type: application/ms-excel");
			resp.setCharacterEncoding("tis-620");
			printTextFile = ","+","+","+","+title+System.getProperty("line.separator")+
					","+SearchNameCode+","+code+
					","+betweenDate+","+dateCheckinShow+
					","+toDate+","+dateCheckoutShow+
					","+typeCheckin+","+type[0]+
					","+typeresv+","+status[0]+","+System.getProperty("line.separator")+
					","+System.getProperty("line.separator")+
					"#"+","+groupCode+","+ReservationId+","+groupGuestName+","+checkInString+","+checkOutString+","+statusString+","+stayDuration+","+typeRoom+System.getProperty("line.separator")+
					""+TextCsv;
			resp.getWriter().println(printTextFile);
		}else{
		  try {
		    Document document = new Document();
		    document.setMargins(10, 10, 30, 10); 
		    FontFactory.register("fonts/angsa.ttf", "angsa"); 
            Font fontHead = FontFactory.getFont("angsa", BaseFont.IDENTITY_H, 
        		   BaseFont.EMBEDDED, 12,Font.BOLD);
            Font fontFil = FontFactory.getFont("angsa", BaseFont.IDENTITY_H, 
        		   BaseFont.EMBEDDED, 10,Font.BOLD);
            Font fontFildata = FontFactory.getFont("angsa", BaseFont.IDENTITY_H, 
        		   BaseFont.EMBEDDED, 10);
            Font fontData = FontFactory.getFont("angsa", BaseFont.IDENTITY_H, 
        		   BaseFont.EMBEDDED, 10); 
           	PdfWriter.getInstance(document, resp.getOutputStream());
		   	document.open();
		   	Image logo = Image.getInstance("images/ihotel.jpeg");
		   	logo.scaleAbsolute(100, 100);
		   	logo.setAbsolutePosition(50f, 700f);
	        document.add(logo);
	        //detail Hotel
	        Paragraph paragraph2 = new Paragraph();
            paragraph2.setSpacingAfter(10);
            paragraph2.setAlignment(Element.ALIGN_CENTER);
            paragraph2.setIndentationLeft(400);
            paragraph2.add(new Paragraph("iHotel",fontHead));
            paragraph2.add(new Paragraph("................................",fontData));
            paragraph2.add(new Paragraph("Thako - 48000",fontData));
            paragraph2.add(new Paragraph("Nakhon Phanom, Thailand",fontData));
            paragraph2.add(new Paragraph("Phone: +6642543355",fontData));
            paragraph2.add(new Paragraph("Fax: +6642543377",fontData));
            paragraph2.add(new Paragraph("Email: ihotelthailands@gmail.com",fontData));
            paragraph2.add(new Paragraph("Website: www.ihotel.co.th",fontData));
            document.add(paragraph2);
            //Header
            PdfPTable tableHeader = new PdfPTable(1);
            tableHeader.setWidthPercentage(50);
            PdfPCell cH = new PdfPCell(new Phrase(title,fontHead));
            cH.setHorizontalAlignment(Element.ALIGN_CENTER);
            cH.setBorder(Rectangle.NO_BORDER);
		    tableHeader.addCell(cH).isNoWrap();
		    //Filter
		    PdfPTable tableFilter = new PdfPTable(10);
		    tableFilter.setWidthPercentage(100);
		    float[] widthFil = new float[] { 2f, 1f, 1.5f, 1f,0.3f, 1f, 1.2f, 0.9f,1.15f , 0.9f };
		    tableFilter.setWidths(widthFil);
            PdfPCell cF = new PdfPCell(new Phrase(SearchNameCode,fontFil));
            cF.setHorizontalAlignment(Element.ALIGN_CENTER);
            cF.setBorder(Rectangle.NO_BORDER);
            tableFilter.addCell(cF).isNoWrap();
            cF = new PdfPCell(new Phrase(code,fontFildata));
            cF.setHorizontalAlignment(Element.ALIGN_LEFT);
            cF.setBorder(Rectangle.NO_BORDER);
            tableFilter.addCell(cF).isNoWrap();
            cF = new PdfPCell(new Phrase(betweenDate,fontFil));
            cF.setHorizontalAlignment(Element.ALIGN_LEFT);
            cF.setBorder(Rectangle.NO_BORDER);
            tableFilter.addCell(cF).isNoWrap();
            cF = new PdfPCell(new Phrase(dateCheckinShow,fontFildata));
            cF.setHorizontalAlignment(Element.ALIGN_LEFT);
            cF.setBorder(Rectangle.NO_BORDER);
            tableFilter.addCell(cF).isNoWrap();
            cF = new PdfPCell(new Phrase(toDate,fontFil));
            cF.setHorizontalAlignment(Element.ALIGN_LEFT);
            cF.setBorder(Rectangle.NO_BORDER);
            tableFilter.addCell(cF).isNoWrap();
            cF = new PdfPCell(new Phrase(dateCheckoutShow,fontFildata));
            cF.setHorizontalAlignment(Element.ALIGN_LEFT);
            cF.setBorder(Rectangle.NO_BORDER);
            tableFilter.addCell(cF).isNoWrap();
            cF = new PdfPCell(new Phrase(typeCheckin,fontFil));
            cF.setHorizontalAlignment(Element.ALIGN_LEFT);
            cF.setBorder(Rectangle.NO_BORDER);
            tableFilter.addCell(cF).isNoWrap();
            cF = new PdfPCell(new Phrase(type[0],fontFildata));
            cF.setHorizontalAlignment(Element.ALIGN_LEFT);
            cF.setBorder(Rectangle.NO_BORDER);
            tableFilter.addCell(cF).isNoWrap();
            cF = new PdfPCell(new Phrase(typeresv,fontFil));
            cF.setHorizontalAlignment(Element.ALIGN_LEFT);
            cF.setBorder(Rectangle.NO_BORDER);
            tableFilter.addCell(cF).isNoWrap();
            cF = new PdfPCell(new Phrase(status[0],fontFildata));
            cF.setHorizontalAlignment(Element.ALIGN_LEFT);
            cF.setBorder(Rectangle.NO_BORDER);
            tableFilter.addCell(cF).isNoWrap();
            //Data
		   	PdfPTable table = new PdfPTable(9);
		    table.setWidthPercentage(100);
	        float[] widths = new float[] { 0.5f, 2f, 2f, 2f, 2f, 2f, 1.2f, 3.5f, 3f };
	        table.setWidths(widths);
		    PdfPCell c1 = new PdfPCell(new Phrase("#",fontHead));
		    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
		    c1.setBorder(Rectangle.NO_BORDER);
		    table.addCell(c1).isNoWrap();
		    c1 = new PdfPCell(new Phrase(groupCode,fontHead));
		    c1.setHorizontalAlignment(Element.ALIGN_LEFT);
		    c1.setBorder(Rectangle.NO_BORDER);
		    table.addCell(c1).isNoWrap();
		    c1 = new PdfPCell(new Phrase(ReservationId,fontHead));
		    c1.setHorizontalAlignment(Element.ALIGN_LEFT);
		    c1.setBorder(Rectangle.NO_BORDER);
		    table.addCell(c1).isNoWrap();
		    c1 = new PdfPCell(new Phrase(groupGuestName,fontHead));
		    c1.setHorizontalAlignment(Element.ALIGN_LEFT);
		    c1.setBorder(Rectangle.NO_BORDER);
		    table.addCell(c1).isNoWrap();
		    c1 = new PdfPCell(new Phrase(checkInString,fontHead));
		    c1.setHorizontalAlignment(Element.ALIGN_LEFT);
		    c1.setBorder(Rectangle.NO_BORDER);
		    table.addCell(c1).isNoWrap();
		    c1 = new PdfPCell(new Phrase(checkOutString,fontHead));
		    c1.setHorizontalAlignment(Element.ALIGN_LEFT);
		    c1.setBorder(Rectangle.NO_BORDER);
		    table.addCell(c1).isNoWrap();
		    c1 = new PdfPCell(new Phrase(statusString,fontHead));
		    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
		    c1.setBorder(Rectangle.NO_BORDER);
		    table.addCell(c1).isNoWrap();
		    c1 = new PdfPCell(new Phrase(stayDuration,fontHead));
		    c1.setHorizontalAlignment(Element.ALIGN_LEFT);
		    c1.setBorder(Rectangle.NO_BORDER);
		    table.addCell(c1).isNoWrap();
		    c1 = new PdfPCell(new Phrase(typeRoom,fontHead));
		    c1.setHorizontalAlignment(Element.ALIGN_LEFT);
		    c1.setBorder(Rectangle.NO_BORDER);
		    table.addCell(c1).isNoWrap();
		    arrayListpdf.get(0);
		    table.setHeaderRows(1);
		    for(int p =0;p<arrayListpdf.size();p++){
		        String[] datapdf = arrayListpdf.get(p).split("#");
		        for(int input=0;input<datapdf.length;input++){
		        	c1 = new PdfPCell(new Phrase(datapdf[input].trim(),fontData));
		        	c1.setBorder(Rectangle.NO_BORDER);
		        	if(input==6||input==0)
		        		c1.setHorizontalAlignment(Element.ALIGN_CENTER);
		        	else
		        		c1.setHorizontalAlignment(Element.ALIGN_LEFT);
		        	table.addCell(c1);
		        }
		    }
		    document.add(tableHeader);
		    document.add(tableFilter);
		    document.add(table);
		    document.close();
		  }catch(DocumentException e) {e.printStackTrace();}
		}
	}
	public String formatDate(Date dateSend) throws ParseException {
	    SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
		return String.valueOf(sdf.format(dateSend));
	}	
	
	private void InsertGuestResInGroup(HttpServletRequest req,HttpServletResponse resp) throws IOException, EntityNotFoundException, ParseException {
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		long resId = Long.parseLong(req.getParameter("resId"));
		long guestId=Long.parseLong(req.getParameter("guestId"));
		long salutationId =Long.parseLong(req.getParameter("salutationId"));
		String name = req.getParameter("name");
		String lastName = req.getParameter("lastName");
		String phone = req.getParameter("phone");
		GuestLogic guestLogic = new GuestLogic(req,resp);
		GuestData gd = new GuestData();
		ReservationLogic reservationlogic = new ReservationLogic(req,resp);
		Reservation res = reservationlogic.GetReservation(resId);
		long guestAmount = res.getAdult()+res.getChild();
		long maxocc = res.getRoomType().getMaxOccupancy();
		if(guestAmount<maxocc){
			Guest gs = new Guest();
			if(guestId==0){
				gs = guestLogic.AddGuest(salutationId, name, lastName,phone,"");
				guestId=gs.getId();
				gd = guestLogic.FillGuestData(gs,res);
			}else
			{
				 gs = guestLogic.GetGuest(guestId);
				 gd = guestLogic.FillGuestData(gs,res);
			}
			String guestIds = String.valueOf(guestId);
			reservationlogic.EditGuest(resId, guestIds);
			reservationlogic.EditAdditionalGuest(hotelId, resId, guestIds);
		}
		else
			gd = null;
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(gd));
	}

	private void IncreaseReservation(HttpServletRequest req,HttpServletResponse resp) throws EntityNotFoundException, ParseException, IOException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		long resId = Long.parseLong(req.getParameter("resId"));
		long days = Long.parseLong(req.getParameter("days"));
		
		HashMap<String, Object> obj =new ReservationLogic(req,resp).IncreaseReservation(hotelId,resId,days);
		
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void testLogicReservation(HttpServletRequest req,HttpServletResponse resp) throws EntityNotFoundException, ParseException, IOException {
		//HttpSession session = req.getSession(true);
		//long hotelId = 1;
		//if (session.getAttribute("hotelId") != null)
		//	hotelId = (Long) session.getAttribute("hotelId");
		long resId = Long.parseLong(req.getParameter("resId"));
			
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		Reservation res = resLogic.GetReservation(resId);
		List<SubReservation> sublist = res.getSubReservationList();
		if(sublist.size() ==0){
			SubReservation aa = new SubReservation();
			aa.CloneReservation(res);
			sublist.add(aa);
		}
		Room obj =resLogic.AutoMoveRoomWithSellRoom(sublist.get(0));
		
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
}